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

前端 未结 9 939
栀梦
栀梦 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:55

    In case you don't want to use get_called_class() you can use other tricks of late static binding (PHP 5.3+). But the downside in this case you need to have getClass() method in every model. Which is not a big deal IMO.

     $table, 'id' => $id);
            return new $class($data);
        }
    
        public function __construct($data)
        {
            echo get_class($this) . ': ' . print_r($data, true) . PHP_EOL;
        }
    }
    
    class User extends Base
    {
        protected static $_table = 'users';
    
        public static function getClass()
        {
            return __CLASS__;
        }
    }
    
    class Image extends Base
    {
        protected static $_table = 'images';
    
        public static function getClass()
        {
            return __CLASS__;
        }
    }
    
    $user = User::find(1); // User: Array ([table] => users [id] => 1)  
    $image = Image::find(5); // Image: Array ([table] => images [id] => 5)
    

提交回复
热议问题