假设以下代码:
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的输出,即: 如何强制父构造函数方法始终寻找子类名称?
答案 0 :(得分:4)
您可以使用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