1

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!

alex
  • 479,566
  • 201
  • 878
  • 984
Itay
  • 31
  • 1
  • 3

4 Answers4

7

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()
Saso.Filipovic
  • 117
  • 2
  • 1
  • Point 1 is no longer true now - static function can now be abstract again starting from PHP 7.0 - however `self::getName()` needed to change to `static::getName()` in order for it to work. RFC: https://wiki.php.net/rfc/reclassify_e_strict#abstract_static_methods – Michael Tsang May 28 '20 at 03:58
6

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

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.

alex
  • 479,566
  • 201
  • 878
  • 984
1

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.

Community
  • 1
  • 1
David Souther
  • 8,125
  • 2
  • 36
  • 53