Broad Network


Passing and Returning Reference in PHP

PHP References - Part 2

Foreword: In this part of the series, I talk about the passing and return by reference, with PHP function.

By: Chrysanthus Date Published: 2 Dec 2018

Introduction

This is part 2 of my series, PHP Reference. In programming, when the argument to a function is a reference, we say you have passed a reference to the function. In this part of the series, I talk about the passing and return by reference, with PHP function. You should have read the previous part of the series before coming here, as this is the continuation.

Passing by Reference
In this section, I talk about passing scalars, arrays and objects. When you pass a variable, the normal way, to a function, you end up with 2 copies of the variable (memory regions) within the function definition. Read and test the following code:

<?php

    $var = "I love you.";

     function myFn($vr)
        {
            echo $vr, '<br>';
            $vr = "I hate you.";
            echo $vr, '<br>';
        }

    myFn($var);
    echo $var;

?>

The variable, $var with content, "I love you." is passed to the function. The first statement in the function displays the content. The content of the parameter of the function is changed within the function definition, then displayed. The output is:

    I love you.
    I hate you.
    I love you.

You end up with $vr having one value and $var having another. Both were supposed to have the same value (supposed to be referring to the same region). Note that you end up with 2 memory regions relating to $var. If that is what you want, there is no problem. However, if you want to economize memory, then you have to pass by reference.

Use & in the parameter list to have only one copy of the value. Try the following code, which illustrates this with & :

<?php

    $var = "I love you.";

     function myFn(&$vr)
        {
            global $var;

            echo $var, '<br>';
            $vr = "I hate you.";
            echo $var, '<br>';
        }

    myFn($var);

?>

Note the use of the global reserved word. Note that & has been used only in the parameter list, not even for the parameter in the function definition, not for the argument in the function call. In the function definition, the variable declared outside was used in the print (echo) statements, and not $vr of the argument list. The value was changed through the parameter. The output is:

    I love you.
    I hate you.

with only 1 copy and not 2.

Passing without Pre-declaration
In the above code samples the variable outside the function was pre-declared. The following code shows that the variable does not have to be pre-declared:

<?php

     function myFn(&$vr)
        {
            $vr = "I hate you.";
            echo $vr, '<br>';
        }

    myFn($var);
    echo $var, '<br>';

?>

The output is:

    I hate you.
    I hate you.

This code also shows that a variable started in a function call as argument, can be seen outside the function, if it is passed as argument.

In the same light, you can pass an object to a function, while instantiating the object in the function call as argument. Read and test the following code:

<?php

    class Cla
        {
            public $prop = 'We are the world.';
        }

     function myFn(&$ob)
        {
            echo $ob->prop, '<br>';
        }

    myFn(new Cla());

?>

The output is:

    We are the world.

The reserved word, new returns some kind of a reference. So the following code without & in the parameter list, still works:

<?php

    class Cla
        {
            public $prop = 'We are the world.';
        }

     function myFn($ob)
        {
            echo $ob->prop, '<br>';
        }

    myFn(new Cla());

?>

The output is:

    We are the world.

Issue with global
If you assign a reference to a variable declared outside a function definition, but declared global inside the function definition, the reference will be visible only inside the function definition. Read and test the following code:

<?php

    $var = "I love you.";

     function myFn()
        {
            global $var;

            echo $var, '<br>';
            $vrr = "I hate you.";
            $var = &$vrr;
            echo $var, '<br>';
        }

    myFn($var);
    echo $var;

?>

The output is:

    I love you.
    I hate you.
    I love you.

If you want the effect to be seen outside the function, use the superglobal array, $GLOBALS as follows:

<?php

    $va = "I love you.";

     function myFn()
        {
            echo $GLOBALS['va'], '<br>';
            $vrr = "I hate you.";
            $GLOBALS['va'] = &$vrr;
            echo $GLOBALS['va'], '<br>';
        }

    myFn($va);
    echo $va;

?>

The output is:

    I love you.
    I hate you.
    I hate you.

Returning a Reference
In PHP, returning of reference, is an awkward scheme.

A function can return a reference. However, to return a reference, you have to indicate so, to the function definition and function call, as follows:

<?php

    $var = "I love you.";
     function &hisFn()
        {
            global $var;

            $vrrr = &$var;
            return $vrrr;
        }

    $ret = &hisFn();
    $ret = "I hate you.";

    echo $var;

?>

$vrrr is a reference. Note the use of & in the two places for the function name. The output is:

    I hate you.

$var and $vrrr are now pointing to the same memory location.

$this->value
$this->value is a reference to a member of an object. Read and test the following code:

<?php

    class Cla
        {
            public $prop = 'We are the world.';

            public function &mthd()
                {
                    return $this->prop;
                }
        }

    $obj = new Cla();    
    $ret = &$obj->mthd();
    $ret = "You are the earth.";
    echo $obj->prop;

?>

Note the use of & for the function definition and function call. The output is:

    You are the earth.

new Class()
In PHP "$this->value" is considered as a variable, while "new Class()" is an expression. Though "new Class()" returns a reference, in PHP, you cannot use an espression like that in the return statement, to return a reference. In the following code, a copy and not the reference, is returned:

<?php

    class Cla
        {
            public $prop = 'We are the world.';

            public function &mthd()
                {
                    return new Cla();
                }
        }

    $obj = new Cla();    
    $ret = &$obj->mthd();
    $ret->prop = "You are the earth.";
    echo $obj->prop;

?>

The output is:

    We are the world.

We had to end up with two copies, since there are two instantiations (creations) of the object.

Attempting return &$var
While "return new Class()" returns a copy, the expression, "return &$var" causes a fatal error. I tried the code:

<?php

    $var = "I love you.";
     function &hisFn()
        {
            global $var;

            return &$var;
        }

    $ret = &hisFn();
    $ret = "I hate you.";

    echo $var;

?>

and I had:

    Parse error: syntax error, unexpected '&', expecting ';' in C:Apache24htdocstemp.php on line 8

An Array Name is a Reference
You can return an array name as a reference. The following code illustrates this:

<?php

    $arr = array('Apple' => "purple", 'Banana' => "yellow", 'Pear' => "green");

     function &hisFn()
        {
            global $arr;

            return $arr;
        }

    $ret = &hisFn();
    echo $arr['Pear'], '<br>';
    $ret['Pear'] = 'white';
    echo $arr['Pear'];

?>

Note the use of global. The output is:

    green
    white

You do not have to precede $arr with &. Even if you do, you will have an error.

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