强制父方法使用子 class 值

Forcing parent method to work with child class values

假设以下代码:

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

然而这里:

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

问题: 我如何在 EXAMPLE_2 中实现 EXAMPLE_1 的输出,即: 如何强制父构造函数方法始终查找子 class 名称?

您可以使用 get_called_class() 而不是 get_class():

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

更多信息:https://php.net/manual/en/function.get-called-class.php