php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #77537 Unexpected behavior, when using static in constructor
Submitted: 2019-01-29 09:11 UTC Modified: -
Votes:1
Avg. Score:3.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: dirk dot gerigk at atraveo dot com Assigned:
Status: Open Package: Class/Object related
PHP Version: 7.2.14 OS: Windows 10
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [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

Patches

Add a Patch

Pull Requests

Add a Pull Request

 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Wed Jul 17 07:01:25 2019 UTC