Req #77537 [Opn->Dup]: Unexpected behavior, when using static in constructor
| From: | nikic@php.net | Date: | Thu, 18 Feb 2021 11:01:26 +0000 |
| Subject: | Req #77537 [Opn->Dup]: Unexpected behavior, when using static in constructor | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-232237@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=77537&edit=1
ID: 77537
Updated by: nikic@php.net
Reported by: dirk dot gerigk at atraveo dot com
Summary: Unexpected behavior, when using static in
constructor
-Status: Open
+Status: Duplicate
Type: Feature/Change Request
Package: Class/Object related
Operating System: Windows 10
PHP Version: 7.2.14
Block user comment: N
Private report: N
New Comment:
In PHP, static variables are bound to a specific method -- if the method is inherited, then it also
gets separate static variables. This means that C::__construct() has static variables independent of
A::__construct().
I'm going to close this as a duplicate of bug #74198, because the behavior of static variables
in methods and their interaction with inheritance is currently not documented.
Previous Comments:
------------------------------------------------------------------------
[2019-01-29 09:11:40] dirk dot gerigk at atraveo dot com
Description:
------------
Unexpected behavior in extended class, when using static variable in constructor and call the method
directly
I was testing the concept of immutable classes and was coming to an point where i called the
__construct method directly. I injected an static $var in the method and found that unexpected
behavior. I seems that the C class that not defines an constructor once call the constructor with
the previews incremented static var, but the direct call of the method gets an fresh static var.
I think it is not normal to call the constructor directly as method, but when it is it should have
same result as the class B.
The call of $c->__construct(); should get 6 not 1.
Or there any explanation to this?
Test script:
---------------
class A {
public function __construct(){
static $test = 0;
print (++$test);
}
}
class B extends A {
public function __construct(){
parent::__construct();
}
}
class C extends A {}
$a = new A;
$a->__construct();
$b = new B;
$b->__construct();
$c = new C;
$c->__construct();
Expected result:
----------------
123456
Actual result:
--------------
123451
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=77537&edit=1