M
M
Memorivardo2016-07-20 14:50:08
PHP
Memorivardo, 2016-07-20 14:50:08

How to get class name from static method?

There is code similar to this:

class A extends B {}
abstract class B {
  static function show(){
    //здесь хочу получить имя класса, от которого был вызван метод
  }
}

class D{
  public function init() {
    A::show();
  }
}

$object = new D();
D->init();

Problem: inside the show() function, you need to get the name of the class from which it was directly called. So far, all my searches and attempts have resulted in either getting the class in which this function is defined (B) or the class in which the call occurred (D).
I know the option in which the problem is solved, but for it I need to prescribe the class name as a property of this class, which I don’t want to do categorically.
Who knows the solution to this problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Max, 2016-07-20
@Memorivardo

I still don’t understand that you want to get
AB or D at the output
here for A

class A extends B {}
abstract class B {
    public static function show(){
        echo static::class;
        //здесь хочу получить имя класса, от которого был вызван метод
    }
}

class D{
    public function init() {
        A::show();
    }
}

$object = new D();
$object->init();

Here In
class A extends B {}
abstract class B {
    public static function show(){
        echo self::class;
        //здесь хочу получить имя класса, от которого был вызван метод
    }
}

class D{
    public function init() {
        A::show();
    }
}

$object = new D();
$object->init();

G
Grigory Esin, 2016-07-20
@xotey83

get_called_class(): php.net/manual/function.get-called-class.php
What you want is called "late static binding".
Introduced in PHP 5.4

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question