Static keyword doesn't work inside PHP generator function -
it seems static
keyword not work inside generator functions? in php 5.5:
function static_fn () { static $p = 0; echo "\nstatic_fn: p = " . $p . "\n" ; $p++; } echo "calling static_fn()\n"; static_fn(); echo "calling static_fn()\n"; static_fn(); function static_gen() { static $p = 0; echo "\nstatic_gen: p = " . $p . "\n" ; yield $p; } echo "calling static_gen()\n"; foreach(static_gen() $stuff) { echo $stuff . "\n"; } echo "calling static_gen()\n"; foreach(static_gen() $stuff) { echo $stuff . "\n"; }
i result
calling static_fn() static_fn: p = 0 calling static_fn() static_fn: p = 1 calling static_gen() static_gen: p = 0 0 calling static_gen() static_gen: p = 0 0
that is, static
keyword worked static_fn
function returned 0 , 1 consecutive calls, did not work static_gen
function reinitialised 0 in each call.
does know why so, , how 1 might work around replicate static variables in generator?
try this:
function static_gen() { static $p = 0; #initialised while ($p < 10) { #yield while $p smaller 10 $p++; #increased echo "\nstatic_gen: p = " . $p . "\n" ; yield $p; #yield value } }
that work.
sidenote: generator function must yield values long values given. function must provide in 1 or other way.
Comments
Post a Comment