note 97856 deleted from functions.anonymous by nicobn
| From: | nicobn@php.net | Date: | Wed, 03 Nov 2010 21:47:47 +0000 |
| Subject: | note 97856 deleted from functions.anonymous by nicobn | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-173728@lists.php.net to get a copy of this message | ||
Note Submitter: whatrevolution ought yahoo daught calm
----
PHP 5.3.2-1ubuntu4:
You can't feed array values to this object as arguments.
<?php
$tmp[0] = 1;
$tmp[1] = 1;
$tmp[2] = 1;
$tmp[3] = function($zero,$one,$two) use ($tmp[0],$tmp[1],$tmp[2]) {};
?>
Result:
PHP Parse error: syntax error, unexpected '[', expecting ',' or ')'
The variable you store this object in effectively becomes a function name, with some traits of an
object, such as internal array storage for its properties. So you can't echo the variable to
get the return.
<?php
$tmp0 = 1;
$tmp1 = 1;
$tmp2 = 1;
$tmp3 = function($zero,$one,$two) use ($tmp0,$tmp1,$tmp2) {
return $tmp0+$tmp1+$tmp2;
};
echo $tmp3;
?>
Result:
PHP Catchable fatal error: Object of class Closure could not be converted to string
Change echo to var_dump() and see what you actually have:
object(Closure)#1 (2) { ["static"]=> array(3) { ["tmp0"]=> int(1)
["tmp1"]=> int(1) ["tmp2"]=> int(1) } ["parameter"]=>
array(3) { ["$zero"]=> string(10) "" ["$one"]=> string(10)
"" ["$two"]=> string(10) "" } }
The transferance of argument variable names to "static" array keys may explain the first
point of this note.
However, this "object" is not of a form you may first expect, either.
<?php
...
echo $tmp3['tmp0'];
?>
Result:
Fatal error: Cannot use object of type Closure as array
<?php
...
echo $tmp3->tmp0;
?>
Result:
Catchable fatal error: Closure object cannot have properties
This function works as:
<?php
$tmp0 = 1;
$tmp1 = 1;
$tmp2 = 1;
$tmp3 = function($zero,$one,$two) use ($tmp0,$tmp1,$tmp2) {
return $zero+$one+$two+$tmp0+$tmp1+$tmp2;
};
echo '<pre>';
echo $tmp3(1,1,1); // 6
echo "\n\n";
$tmp0 = 0;
echo $tmp3(1,1,1); // 6
echo "\n\n";
$tmp1 = 0;
echo $tmp3(1,1,1); // 6
echo "\n\n";
$tmp2 = 0;
echo $tmp3(1,1,1); // 6
echo "\n\n";
echo '</pre>';
?>
The "use ($tmp0,$tmp1,$tmp2)" portion is not a reference to those variable values external
to the function, but rather is a passage of arguments, and the class borrows the original variable
names for its own property names.