【问题标题】:Forcing parent method to work with child class values强制父方法使用子类值
【发布时间】:2019-06-20 18:16:20
【问题描述】:

假设以下代码:

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的输出,即: 如何强制父构造方法总是寻找子类名?

【问题讨论】:

    标签: php oop inheritance prototypal-inheritance


    【解决方案1】:

    您可以使用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

    【讨论】:

      猜你喜欢
      • 2012-03-08
      • 2017-11-18
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2011-05-21
      • 2021-06-09
      • 2017-05-14
      相关资源
      最近更新 更多