Bug #73872 [Opn->Csd]: Static method variable state depends on file include
| From: | nikic@php.net | Date: | Thu, 18 Feb 2021 10:57:40 +0000 |
| Subject: | Bug #73872 [Opn->Csd]: Static method variable state depends on file include | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-232236@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=73872&edit=1
ID: 73872
Updated by: nikic@php.net
Reported by: sc at shpock dot com
Summary: Static method variable state depends on file include
-Status: Open
+Status: Closed
Type: Bug
Package: Class/Object related
Operating System: Linux
PHP Version: 7.0.14
-Assigned To:
+Assigned To: nikic
Block user comment: N
Private report: N
New Comment:
This issue has been fixed in PHP 8.1 with https://github.com/php/php-src/commit/5d160e309ed207e618d49029e51c9c2dc2c5e61c.
The reason why the include makes a difference is that without the include, the CihldClass is early
bound, which means that it is actually registered before the call to $parent->getSomething().
After the aforementioned fix, the call to getSomething() no longer influences the behavior.
Previous Comments:
------------------------------------------------------------------------
[2017-01-05 13:34:18] sc at shpock dot com
Description:
------------
Setup: a parent class which defines a static variable in a method. The static variable is
initialized with NULL and set to some value on the first method call. Then, a child class calls the
same (inherited) method.
If the child class definition is in the same file as the parent class definition, this works as
expected. However, if the child class definition is loaded from a separate file and this file is
loaded after(!) the first call to the method which sets the static variable, the static variable
seems to be "shared" between both classes.
I'm really curious about an explanation in case this is not a bug because i would like to
understand the concept. Thank you!
Test script:
---------------
class ParentClass
{
protected $something = 'parent';
public function getSomething()
{
static $cache;
return $cache !== null
? $cache
: $cache = $this->something;
}
}
$parent = new ParentClass();
var_dump($parent->getSomething()); // expected: 'parent'; returned: 'parent'
include 'child.php';
# content of child.php:
//class ChildClass extends ParentClass
//{
// protected $something = 'child';
//}
$child = new ChildClass();
var_dump($child->getSomething()); // expected 'child'; returned 'parent'
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=73872&edit=1