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

前端 未结 4 518
被撕碎了的回忆
被撕碎了的回忆 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:32

    This is certainly possible using static::class (or get_class($this) or get_called_class()) in the base class to get the name of the child (which is initially called at runtime):

    Produces:

    string(3) "Foo"
    string(3) "Foo"
    string(3) "Foo"
    string(3) "Bar"
    string(3) "Bar"
    string(3) "Bar"
    string(3) "Baz"
    string(3) "Baz"
    string(3) "Baz"
    

    This is called late static binding. Here's a demo of the above.

提交回复
热议问题