|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2019-01-29 09:11 UTC] 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
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Oct 26 12:00:01 2025 UTC |
I have tested in another way class A { public function test(){ static $test = 0; print (++$test); } public function __construct(){ $this->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(); and the result is 121212 So, for now i will keep in mind: * dont mess with the constuctor of a class * do not use static variables in a constructor Thanks for the time and work