2013-01-17 133 views
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"); 
     } 
    } 
} 
從可能的複製粘貼/格式化錯誤

除此之外,上面的代碼不具備parent`s靜態變量,所以我想我的地方缺少一個細節。

任何有關正在發生的事情的線索都是值得讚賞的。

+0

哪個版本的PHP? – Eric

+0

[Works for me](http://sandbox.onlinephpfunctions.com/code/27c3e6f4075ac9e9c306bdfe9203df4d7b327884)。你忘了從'UserAbstract'派生'TrexUserAbstract'嗎? – Eric

+0

啊人。這很奇怪,因爲除了我使用autoloade之外,我的代碼與您的小提琴完全相同。我有版本5.3.2-1, – stefgosselin

回答

1

我看到幾個錯誤。你的意思是?

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

UPDATE

需要明確的是,作爲@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"; 
+0

是的。感謝朋友,問題是問題。這個如果只是爲了獲得快速的調試輸出,只是爲了表明當前的熱度是成功還是失敗。再次感謝。 – stefgosselin

+0

@stefgosselin o/\時間慶祝! yabadadoo!大聲笑 –