Broad Network


Returning Values in PHP Function

PHP Functions with Security Considerations - Part 4

Foreword: In this part of the series I talk about Returning Values in PHP Function.

By: Chrysanthus Date Published: 12 Nov 2018

Introduction

This is part 4 of my series, PHP Functions with Security Considerations. In this part of the series I talk about Returning Values in PHP Function. You should have read the previous parts of the series, before coming here, as this is the continuation.

Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. The return statement causes the function to end its execution immediately and pass control back to the line from which it was called.

Do not confuse between the return statement and the echo (or print) statement.

Returning Single Value
Try the following code:

<?php

    function square($a)
        {
             $b = $a * $a;

            return $b;
        }

    $z = square(3);

    echo $z;

?>

The output is;

    9

Returning more than One Value
If you want to return more than one value, return an array. The following swap function illustrates this:

<?php

    function swap($a, $b)
        {
            $temporary = $b;
            $b = $a;
            $a = $temporary;

            return array('a'=>$a, 'b'=>$b);
        }

    $arr = swap(2, 3);

    foreach($arr as $key => $value)
        echo $key, ' => ', $value, '<br>';

?>

The output is:

    a => 3
    b => 2

Returning an Object
You return an object in a similar way that you return an array. Try the following:

<?php

    function fn()
        {
            class Classe
                {
                    // property declaration
                    public $color = 'blue';
                }

            $obj = new Classe();

            return $obj;
        }

    $obje = fn();
    echo $obje->color;

?>

The output is:

    blue

Return Type Declarations
With return type declaration, you specify the return type that the function must return. If you return a type different from what you have specified, you end up with a fatal error, and the program stops running; so that you do not have wrong results. Try the following code:

<?php

    function myFn($a, $b) : float
        {
            $joint = $a . $b;
            return $joint;
        }

    $ret = myFn('some', ' text');
    echo $ret;

?>

The output is a fatal error (message).

Now try the following where the return type is the same as the type (float) declared

<?php

    function myFn($a, $b) : float
        {
            $sum = $a + $b;
            return $sum;
        }

    $ret = myFn(2.5, 4);
    echo $ret;

?>

The output is:

    6.5

You declare the return type beginning with a colon, after the closing parenthesis for the parameters. Then you write the name for the type you want to return.

Types and Values
The return types with allowed values are as follows:

TYPE                          Values
bool:                            value must be a boolean value.
float:                            value must be a floating point number.
int:                              value must be an integer.
string:                          value must be a string.
array:                           value must be an array.
object:                         value must be an object.
iterable:                        value must be either an array or an instanceof Traversable.
callable:                       value must be a valid callable.
Class name:                 value must be an instanceof the given class.
Interface name:             value must be an instanceof the  interface.
self :                            value must be an instanceof the same class as the one the method is defined on.

Some scalar type have aliases. For example, the alias of float is double; the alias of bool is Boolean. Aliases are not supported in this scheme.

Strict Typing
Type declaration alone as solution still has its limits. Try the following code:

<?php

    function myFn($a, $b) : int
        {
            $sum = $a + $b;
            return $sum;
        }

    $ret = myFn(2.7, 3);
    echo $ret;

?>

The output is:

    5

instead of 5.7. The declared return type is, int. However PHP converts the float, 5.7 to integer, 5 by truncating the decimal part (which is not rounding - not correct).

In many such cases, you will have a satisfactory result. However, there is a limit to every thing. To really enforce type declaration, you have to start the file with the statement:

    declare(strict_types=1);

Try the following code:

<?php

    declare(strict_types=1);

    function myFn($a, $b) : int
        {
            $sum = $a + $b;
            return $sum;
        }

    $ret = myFn(2.7, 3);
    echo $ret;

?>

I tried the code and I had a fatal error; the script stopped working, as it should.

So, type declaration works at the limit, in strict mode. Try the following, where the name (float) of the correct return type, has been used:

<?php

    declare(strict_types=1);

    function myFn($a, $b) : float
        {
            $sum = $a + $b;
            return $sum;
        }

    $ret = myFn(2.7, 3);
    echo $ret;

?>

The output is:

    5.7

best result.

Return Type Declaration and Included Files
Type the following code and save the file with the name, temp.php :

<?php

    include ("temp2.php");

    $ret = myFn(2.7, 3);
    echo $ret;

?>

Type the following code and save it with the name temp2.php in the same directory as the above file:

<?php

    declare(strict_types=1);

    function myFn($a, $b) : float
        {
            $sum = $a + $b;

            return $sum;
        }

?>

Run the temp.php file. The output is:

    5.7

So, if an included file is in the strict mode for return type declaration, a call for a function in the included file from the main file, will respect the strictness. This is as opposed to argument type declaration, where the strictness is not respected.

That is it for this part of the series. We stop here and continue in the next part.

Chrys


Related Links

Basics of PHP with Security Considerations
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

BACK NEXT

Comments