开发者

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 i开发者_如何学运维nconsistencies, I was wondering if perhaps this pertains to something else.


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.


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


I think the only reason this exist is for allowing to skip trailing parameters in a function call

function test(&$bar = 10)
{
    echo " '$bar' ";
    $bar = $bar*2;
    echo " '$bar' ";
}

test($aaa);     // prints '' '0'     (NULL as string, NULL*2)
echo $aaa;      // prints 0          ($aaa is set to NULL*2)
echo "<br>";

$bbb = 6;
test($bbb);     // prints '6' '12'   (6, 6*2)
echo $bbb;      // prints 12         ($bbb is set to 6*2)
echo "<br>";

test();        // prints '10' '20'
// (uses the default value since the argument was skipped, so: 10, 10*2)

So imho the reason this exist is merely the possibility to have $bar set to some default value inside the function scope when you skip the leading parameter in the function's call

If it's like so I agree with you, the manual should be more precise about this

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜