How to get the name of child class from base class when an object of child class is created

前端 未结 4 493
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 07:21

I want to get the name of my child class in the base class so that whenever an object of child class is created I get the name of the child class in my base class. Something

4条回答
  •  礼貌的吻别
    2021-01-03 07:37

    Yes, to an extent. In PHP 5.5, the ::class class constant was added, which returns the class name of class to which it is applied. You can then use this in conjunction with parent, self, or static. Consider this code:

    foo();
    

    self::class will return the same thing as __CLASS__, the class belonging to the function currently executing (in this case, B).

    parent::class will return the name of the method's parent class (A).

    static::class, by way of Late Static Binding, will return the class name of the method that was actually invoked (D).

    Note, however, that you can not get the immediate child descendent of your current function (C) without using more advanced means (parsing the call stack via debug_backtrace, or via reflection).

提交回复
热议问题