简体   繁体   English

PHP:多态抽象静态方法

[英]PHP: polymorphic abstract static methods

I'm trying to do something like this but i don't succeed. 我正在尝试做这样的事情,但我没有成功。

abstract class Animal 
{ 
    abstract static function getName();
    static function sayName() { echo self::getName(); }
}

thanks! 谢谢!

You have two problems: 您有两个问题:

  1. static functions can't be abstact in php anymore. 静态函数不再是php中的摘要。
  2. As said before, late static binding: as method getName() is defined in child class, you need to access it with static::getName() instead of self::getName() 如前所述,后期静态绑定:由于在子类中定义了方法getName(),因此您需要使用static :: getName()而不是self :: getName()进行访问

如果您已经暗示自己“不成功”的方式,那就太好了,但是我想您正在跨静态绑定绊脚石,需要使用PHP 5.3中引入的后期静态绑定

My guess is maybe you are trying to instantiate an object from that class. 我的猜测可能是您正在尝试实例化该类中的对象。

You can't . 不能 It is an abstract class. 这是一个abstract类。 Subclass it, and then instantiate that. 子类化它,然后实例化它。

That will not succeed- you cannot have an abstract static function. 那不会成功-您不能拥有抽象的静态函数。 See the accepted answer Why does PHP 5.2+ disallow abstract static class methods? 请参阅已接受的答案为什么PHP 5.2+不允许抽象静态类方法? for details on why. 有关原因的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM