A
A
Artyom2019-01-22 10:06:12
PHP
Artyom, 2019-01-22 10:06:12

How does static method inheritance work in php?

How does inheritance work? Why does this code print the label from 'class A'? Wouldn't class B have its own static getMessage method after inheritance, which will take its own getString() through self? Why does he take it from class A?

Class A
{
    public static function getMessage():string
    {
      return 'message - '.self::getString();
    }
    public static function getString():string
    {
      return 'class A';
    }
}


Class B extends A
{
  public static function getString():string
  {
    return 'class B';
  }
}


echo B::getMessage();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2019-01-22
@danyvasnafig

Static references to the current class, such as self:: or __CLASS__ , are evaluated using the class to which this function belongs, as in the place where it was defined
...
Late static binding attempts to remove this limitation by providing a keyword that refers to a class called directly during execution.
Late static binding
Solution:
public static function getMessage(): string
{
  return 'message - ' . static::getString();
}

A
Antony Tkachenko, 2019-01-22
@LemonFox

php.net/manual/ru/language.oop5.late-static-bindin...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question