开发者

PHP: polymorphic abstract static methods

开发者 https://www.devze.com 2023-01-29 14:00 出处:网络
I\'m trying to do something like this but i don\'t succeed. 开发者_C百科 abstract class Animal { abstract static function getName();

I'm trying to do something like this but i don't succeed.

开发者_C百科
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.
  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()


It would have been nice if you'd have given a hint as to how you "don't succeed", but I suppose you're stumbling across static bindings and need to use late static bindings introduced in 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. 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? for details on why.

0

精彩评论

暂无评论...
验证码 换一张
取 消