Bug->Doc #75474 [Opn]: function scope static variables are not bound to a unique function
| From: | requinix@php.net | Date: | Thu, 02 Nov 2017 09:29:30 +0000 |
| Subject: | Bug->Doc #75474 [Opn]: function scope static variables are not bound to a unique function | ||
| References: | 1 | Groups: | php.doc.bugs |
| Request: | Send a blank email to doc-bugs+get-15207@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=75474&edit=1
ID: 75474
Updated by: requinix@php.net
Reported by: nobots dot nospam at example dot org
Summary: function scope static variables are not bound to a
unique function
Status: Open
-Type: Bug
+Type: Documentation Problem
-Package: *General Issues
+Package: Scripting Engine problem
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
> essentially Closure::fromCallable() and $RF->getClosure() should always return the same
> Closure object
I disagree. Both of them are documented to return "new" (Closure::fromCallable) or
"dynamically created" (ReflectionFunction::getClosure) closures - copies of the original,
not shallow references to it. And that implies copies of any static variables it may have, which is
why the first fromCallable shows [0,1] instead of [1].
Regular functions and closures are two separate things: a function is not a closure, and a closure
is not a function*. Creating a closure from a function is not like creating an alias or performing
some sort of import (cf. traits in classes).
How about we clarify the behavior in the documentation?
* It's an object (\Closure) that behaves like a function, and is defined using syntax that
resembles that of a function, but is not actually a function.
Previous Comments:
------------------------------------------------------------------------
[2017-11-02 08:58:58] nobots dot nospam at example dot org
Description:
------------
Every time a closure is generated from a named function, it creates a copy of the static variables
rather than modifying the original named function's ones.
function bar($k, $v){
static $foo = [];
$foo[$k] = $v;
return $foo;
}
var_dump(bar(0, 0));
var_dump(Closure::fromCallable("bar")(1, 1));
var_dump(bar(2, 2));
var_dump(Closure::fromCallable("bar")(3, 3));
$RF = new ReflectionFunction("bar");
var_dump($RF->getClosure()(4, 4));
var_dump(bar(5, 5));
the result after the last bar() call should be [0,1,2,3,4,5]
but it is [0 => 0, 2 => 2, 5 => 5]
essentially Closure::fromCallable() and $RF->getClosure() should always
return the same Closure object:
assert(Closure::fromCallable("foo") === Closure::fromCallable("foo"));
assert($RF->getClosure() === $RF->getClosure());
assert(Closure::fromCallable("foo") === $RF->getClosure());
Unless they are rebound to a different $this or cloned.
Thanks
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=75474&edit=1