1

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

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");  
        }
    }
}

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

任何有关正在发生的事情的线索都值得赞赏。

4

2 回答 2

2

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

于 2013-01-17T22:55:08.290 回答
1

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

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

更新

需要明确的是,正如@stefgosselin 和@supericy 所说,该错误是由 use definedinstead引起的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";
于 2013-01-17T22:56:45.807 回答