Search code examples
php4byref

PHP4 parameter by reference?


I'm quite used to PHP5 but have to write a PHP4 sync script, now I'm doing some digging to find the differences between PHP5 and 4. Problem is that I get alot of contradiction, some sites tell me that PHP4 has no byref whatever and others tell me this problem only occurs when using foreach..

To clarify an example:

function doSomething()
{
    $aMyAr = array();
    $oUser = new User();

    addUser($aMyAr, $oUser);
}

function addUser($aDestArray, $oUser)
{
    $aMyAr[] = $oUser;
}

I know you will be thinking why don't you just run this script yourself and echo/print_r the output? Well for some reasons PHP4 won't run in the latest WAMP/XAMPP (yes I tried a shitload of apache versions that were said to be compatible...)


Solution

  • The change was only that, in PHP4, objects are copied by default, and in PHP5, they're treated as references by default. i.e.:

    $a = new stdClass();
    $a->prop = "original";
    $b = $a;
    
    $b->prop = "changed";
    echo $a->prop;
    
    # PHP4 outputs "original" because $a and $b are different objects
    # PHP5 outputs "changed" because $a and $b are the same object
    

    When you make a function call or use foreach, in PHP4 the object is copied rather than passed by reference.

    To make PHP4 function arguments act like PHP5, you just need to explicitly pass function arguments by reference, i.e.:

    function someFunc(& $someObject) {
      $someObject->prop = "changed";
    }
    
    someFunc($a);
    echo $a->prop; # prints "changed"
    

    So, PHP4 object-oriented code winds up littered with & all over the place (writing true OO code back in the day, this got very tiresome!).

    Another example would be assigning by reference. $b =& $a does with objects in PHP4 what the simple $b = $a does in PHP5.

    Lastly, there's returning by reference. If you create an object inside a function and want to return it (rather than return a copy of it), you'll have to define the function with &, i.e. function &someFunc() {}.

    Again, PHP docs explain the syntax. The best thing to do by far is just not to use PHP4!