lundi 2 mai 2016

Weird behavior on calling __construct using ReflectionClass

I stumble upon a weird behavior I don't think should happen with this code.

class A
{
    public static function call()
    {
        $ref = new ReflectionClass('B');
        $inst = $ref->newInstanceWithoutConstructor();

        var_dump($inst);

        $inst->__construct();
    }

    private function __construct()
    {
        echo 'asd';
    }
}

class B extends A
{
    public function __construct()
    {
        echo 'dsa';
    }
}

B::call();

new B;

When I call B::call(); I thought the code should be echoing dsa but it is echoing asd. Also, var_dump returns object(B)#4 (0) { } which is the class overriding A::__construct. Any thoughts on why this is happening?

Things I made to get to an understanding:

  1. I notice if I change accessibility of the A::__construct to protected or public, B::__construct is called instead.
  2. If I instantiate with new B; like in my sample, it will call B::__construct whether A::__construct is private or not.

Today, I am looking for an explanation to understand if this behavior should be expected from ReflectionClass in PHP. I have no specific usecase to provide for this situation.





Aucun commentaire:

Enregistrer un commentaire