Search code examples
phpoopinheritanceprototypal-inheritance

Forcing parent method to work with child class values


Assuming following code:

EXAMPLE_1

class Parent_Class {}

class Child_Class extends Parent_Class {
    public $class_name;

    public function __construct() {
      $this->class_name = get_class();
    }
}

$child_instance = new Child_Class();
echo $child_instance->class_name;

/// output will be : 
/// Child_Class

However here:

EXAMPLE_2

class Parent_Class {
    public $class_name;

    public function __construct() {
        $this->class_name = get_class();
    }
}

class Child_Class extends Parent_Class {
    public $class_name;

}

$child_instance = new Child_Class();
echo $child_instance->class_name;

/// output will be:
/// Parent_Class

Question: How I can achieve output from EXAMPLE_1 in EXAMPLE_2 ie: how to force the parent constructor method to always look for the child class name?


Solution

  • You can use get_called_class() instead of get_class():

    class Parent_Class
    {
        public function __construct()
        {
            $this->class_name = get_called_class();
        }
    }
    

    For more information: https://php.net/manual/en/function.get-called-class.php