Getting the name of a child class in the parent class (static context)

前端 未结 9 930
栀梦
栀梦 2020-11-29 20:19

I\'m building an ORM library with reuse and simplicity in mind; everything goes fine except that I got stuck by a stupid inheritance limitation. Please consider the code bel

9条回答
  •  死守一世寂寞
    2020-11-29 20:37

    I know this question is really old, but for those looking for a more practical solution than defining a property in every class containing the class name:

    You can use the static keyword for this.

    As explained in this contributor note in the php documentation

    the static keyword can be used inside a super class to access the sub class from which a method is called.

    Example:

    class Base
    {
        public static function init() // Initializes a new instance of the static class
        {
            return new static();
        }
    
        public static function getClass() // Get static class
        {
            return static::class;
        }
    
        public function getStaticClass() // Non-static function to get static class
        {
            return static::class;
        }
    }
    
    class Child extends Base
    {
    
    }
    
    $child = Child::init();         // Initializes a new instance of the Child class
    
                                    // Output:
    var_dump($child);               // object(Child)#1 (0) {}
    echo $child->getStaticClass();  // Child
    echo Child::getClass();         // Child
    

提交回复
热议问题