【问题标题】:Class extend from abstract class with same propriety name类从具有相同专有名称的抽象类扩展而来
【发布时间】:2016-03-30 16:38:36
【问题描述】:

这是我的班级声明

abstract class person {
    const NAME='person';
    public static function get_name(){
        return self::NAME;
    }
    abstract public function get_description();
}

class me extends person{
    const NAME = "me";

    public function get_description(){
        return "this describe " . self::NAME;
    }
}

如您所见,const 名称在类 person 和 me 中都声明了两次。 我在“person”类中声明它,因为它在那里我们在方法 get_name() 的实现中使用它 我也在“我”类中声明它,因为我想要得到“我”的名字。

所以当我打电话时

echo me::get_name() 

我希望它返回“我”

实际上它返回“人”,所以我在这里缺少什么,所以它会返回“我”。

谢谢

【问题讨论】:

    标签: php oop inheritance abstract-class


    【解决方案1】:

    将您的抽象方法更改为:

    abstract class person {
        public static function get_name(){
            return static::NAME;
        }
    }
    

    这将在 PHP 中使用后期静态绑定,如文档中所述: http://php.net/manual/en/language.oop5.late-static-bindings.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 2011-11-20
      • 1970-01-01
      相关资源
      最近更新 更多