user2650277 user2650277 - 27 days ago 5
PHP Question

Detect whether a subclass has called a parent class

Suppose i call the parent class of my subclass with

parent::__construct();
.How can i detect whether the parent class have been called by a subclass in the parent class

KBJ KBJ
Answer

I don't know if I understood your question but my suggestion is to set a static variable that's true, in my case $CHILD, in the Child class then use get_called_class in the Parent class and then test the aforementioned static variable.

class Base {

    public function __construct() {
        $child = get_called_class();
        if($child::$CHILD)
        {
            echo "Parent has being called";
        }
    }
}

class Child extends Base {

    public static $CHILD = true;

    public function __constructor()
    {
        parent::__constructor();
    }
}

$child = new Child();

Another approach would be to use debug_backtrace as @icecub suggested