在抽象类中声明的方法中从子节点中获取常量重写

时间:2011-11-02 22:33:19

标签: php oop class reflection constants

我有这个(缩短):

abstract class MyModel
{
    const DBID = "";
    const TOKEN = "";

    public function getDB()
    {
        if(!$this->_DB)
        {
            $c = get_called_class(); // doesn't work pre php 5.3
            echo $c::DBID; // doesn't work pre php 5.3
            echo $c::TOKEN // doesn't work pre php 5.3
        }

        return $this->_qb;
    } 

问题是get_called_class()和$ c :: DBID / TOKEN在php< 5.3

有没有办法可以在与5.2.9兼容的抽象类中完成相同的任务?

2 个答案:

答案 0 :(得分:1)

编辑: 在整个对象实例化过程中,常量并不是真的要改变,您可能需要考虑成员变量。

抽象类无法直接实例化。您可以创建一个子类来扩展抽象类,然后调用getDb()。

abstract class MyModel
{
    private $dbId;
    private $token;

    public function setDbId($dbId)
    {
        $this->dbId = $dbId;
    }

    public function setToken($token)
    {
        $this->token = $token;
    }

    public function getDbId()
    {
        return $this->dbId;
    }

    public function getToken()
    {
        return $this->token;
    }

    public function __construct()
    {
        // All child classes will have the same values
        $this->setDbId('myParentDbId');
        $this->setToken('myParentToken');
    }

    protected function getDb()
    {
        echo $this->getDbId();
        echo $this->getToken();
    }
}

class MyChildModel extends MyModel
{
    // Don't need any methods, just access to abstract parent
    // But if I wanted to override my parent I could do this
    public function __construct()
    {            
        parent::__construct();

        $this->setDbId('myChildDbId');
        $this->setToken('myChildToken');
    }
}

$myChildModel = new MyChildModel();
var_dump($myChildModel->getDb());

答案 1 :(得分:0)

我在PHP 5.2代码库中有一个解决方案,它使用反射从超类中获取子类的常量,但我建议不要这样做,除非它是绝对必要的,因为反射是PHP中相对昂贵的工具。表现。

PHP 5.3在static :: CONST中引入了static关键字,而不是self :: CONST来访问类的静态成员。我从来没有尝试过,但我相信它应该能够做你需要的。在PHP手册中查找后期静态绑定。

对于记录,这是使用反射来获取子类常量的方法的代码。

class SomeClass
{
    /**
     * Get reflection class for item
     * 
     * Get a reflector for this item so that internal constants can be used for the permission checking
     * functions.  This is necessary because of how static binding works prior to PHP 5.3.  
     * 
     * @return ReflectionClass
     */
    protected function getRef ()
    {
        if (!$this -> ref)
        {
            $this -> ref    = new ReflectionClass ($this);
        }
        return ($this -> ref);
    }

    /**
     * Check that the user has permission to create an item of the type this object represents
     *
     * @todo Use late static binding instead of reflection once PHP 5.3 becomes available on the server
     * @return bool True if OK
     */
    public function canCreate ()
    {
        $ref    = $this -> getRef ();
        if ($flag = $ref -> getConstant ('USR_FLAG_CREATE'))
        {
            return (self::$user -> permissions [$flag]);
        }
    }
}