Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification of PHP manual; default values passed by reference

Due to inconsistencies in the PHP manual (as I've posted about before) I'm just inquiring about some clarification.

The Function Arguments page (http://ca2.php.net/manual/en/functions.arguments.php) has the following note:

Note: As of PHP 5, default values may be passed by reference.

Now, I assume this simply means that the following syntax is acceptable:

function foo(&$bar = null){
    // ...
}

However, again due to other inconsistencies, I was wondering if perhaps this pertains to something else.

like image 875
Dan Lugg Avatar asked Sep 07 '11 19:09

Dan Lugg


2 Answers

It means that in PHP 4, using a default value for arguments passed by reference would result in a parse error:

Parse error: syntax error, unexpected '=', expecting ')' in ...

Demo

In PHP5, when no argument is passed, your function will have a normal local variable called $bar initialized to null.

It should probably be reworded to:

Note: As of PHP 5, function declarations may define a default value for argument passed by reference.

like image 137
Ja͢ck Avatar answered Oct 23 '22 21:10

Ja͢ck


it means that when you change bar

$bar = "newvalue";

in function, old (original one) will be affected too

<?php
function foo(&$bar = null){
    $bar = 'newval';
}

$bar = 'oldval, will be changed';
foo($bar);
echo $bar; //RETURNS newval

so if you change any variable passed by reference, it doesn't matter where you changed, source one is changed, too

http://sandbox.phpcode.eu/g/51723

like image 34
genesis Avatar answered Oct 23 '22 21:10

genesis