静态变量不在子类中继承

时间:2013-01-17 22:43:01

标签: php oop static isset defined

由于某种原因,我无法在子类中继承静态变量。以下代码段似乎没问题,但无效。

abstract class UserAbstract {
    // Class variables
    protected $type;
    protected $opts;
    protected static $isLoaded = false;
    protected static $uid = NULL;

    abstract protected function load();
    abstract protected function isLoaded();
}


class TrexUserActor extends TrexUserAbstract {
    // protected static $uid;  // All is well if I redefine here, but I want inheritance
    /**
     * Constructor
     */
    public function __construct() {
        $this->load();  
    }

    protected function load() {
        if (!$this->isLoaded()) {
            // The following does NOT work. I expected self::$uid to be available...
            if (defined(static::$uid)) echo "$uid is defined";
            else echo self::$uid . " is not defined";  

            echo self::$uid;
            exit;

            // Get uid of newly created user
            self::$uid = get_last_inserted_uid();

            drupal_set_message("Created new actor", "notice");
            // Flag actor as loaded
            self::$isLoaded = true;

            variable_set("trex_actor_loaded", self::$uid);
        } else {
            $actor_uid = variable_set("trex_actor_uid", self::$uid);
            kpr($actor_uid);
            exit;
            $actor = user_load($actor_uid);
            drupal_set_message("Using configured trex actor ($actor->name)", "notice");  
        }
    }
}

除了可能的复制粘贴/重新格式化错误之外,上面的代码没有父级的静态变量,所以我想我错过了某处的细节。

对所发生的事情的任何线索表示赞赏。

2 个答案:

答案 0 :(得分:2)

defined仅适用于常量。您应该使用isset

答案 1 :(得分:1)

我看到几个错误。你的意思是?

if (isset(self::$uid))
    echo "\$uid: " . self::$uid . " is defined";
else
    echo "\$uid is not defined";

<强>更新

要明确,正如@stefgosselin和@supericy所说,错误是由使用defined代替isset引起的。在php5.3 +中添加了Late Static Bindings

所以在php5.3 +中这将起作用:

if (isset(static::$uid))
    echo "\$uid: " . static::$uid . " is defined";
else
    echo "\$uid is not defined";

TrexUserActor课程开始,这也会起作用:

if (isset(TrexUserActor::$uid))
    echo "\$uid: " . TrexUserActor::$uid . " is defined";
else
    echo "\$uid is not defined";