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

前端 未结 9 942
栀梦
栀梦 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条回答
  •  猫巷女王i
    2020-11-29 20:35

    Two variations on Preston's answer:

    1)

    class Base 
    {
        public static function find($id)
        {
            $table = static::$_table;
            $class = static::$_class;
            $data = array('table' => $table, 'id' => $id);
            return new $class($data);
        }
    }
    
    class User extends Base
    {
        public static $_class = 'User';
    }
    

    2)

    class Base 
    {
        public static function _find($class, $id)
        {
            $table = static::$_table;
            $data = array('table' => $table, 'id' => $id);
            return new $class($data);
        }
    }
    
    class User extends Base
    {
        public static function find($id)
        {
            return self::_find(get_class($this), $id);
        }
    }
    

    Note: starting a property name with _ is a convention that basically means "i know i made this public, but it really should have been protected, but i couldn't do that and achieve my goal"

提交回复
热议问题