2016-09-29 164 views
1

要麼我太愚蠢,要麼在(這真的是任何編程語言中的基本功能......): 因此,這裏是我的例子問題:PHP:引用靜態變量中的另一個靜態變量

class Test { 
private static $A = "test"; 
private static $B = "This is a " . Test::$A . " to see if it works"; 
} 

我預期的結果變量$B具有值= This is a test to see if it works

但不知何故,我得到這個錯誤:

Parse error: syntax error, unexpected '$A' (T_VARIABLE), expecting identifier (T_STRING) or class (T_CLASS) in /.../class.Test.php on line 4

這是什麼是無法做到或僅僅是一些愚蠢的錯字?我無法找到的錯誤,因爲有一個小時...提前

+2

類屬性不能有動態值另一種解決方案。意思是你不能做你剛做的事。使用'__construct'爲屬性設置動態值。或者是二傳手,無論你喜歡什麼。 – Andrew

+0

你可以用哪種編程語言來做你所做的事情。我不認爲你可以在任何... –

+0

那麼在Java中這樣做沒有問題。我不明白這些值是如何動態的。這顯然是靜態的。變量$ A將總是具有相同的值,所以我不明白爲什麼不能按照我的方式實現這一點。但我有點新的PHP,所以我只是相信你,這是不可能的這樣(我只是有更多的理由,以避免PHP,我可以:) :) – azaryc2s

回答

0

,如果你不希望有另一個CLAS

class TestStatic 
{ 
    private static $A = 'test'; 
    private static $B; 

    //if you want to instantiate the object 
    public function __construct() { 
     self::setB(); 
    } 

    //if you don't want to instantiate the class 
    public static function getB() { 
     self::setB(); 
     return self::$B; 
    } 

    private static function setB() { 
     if (!isset(self::$B)) { 
     self::$B = 'This is a '.self::$A.' to see if it works'; 
    } 
} 

}

echo TestStatic::getB(); 
+1

謝謝!這要儘可能接近我想要的。仍然是一種恥辱,它不符合我的方式:) – azaryc2s

0
  1. 感謝您不能分配動態值類屬性。請參閱manual

  2. 您可以嘗試定義魔法吸氣劑,但是請參閱吸氣劑不能使用靜態屬性。見manual

Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods should not be declared static. As of PHP 5.3.0, a warning is issued if one of the magic overloading methods is declared static.

In PHP 5.3, __callStatic has been added ; but there is no __getStatic nor __setStatic

  • 所以只是我看到的是使用__callStatic選項和訪問您通過靜態魔術方法屬性。請看下面的例子。

    class A { 
    
        public static $A = 'A'; 
    
        public static function __callStatic($name, $arguments) 
        { 
         if ($name== 'B') { 
         return B::$B; 
         } 
        } 
    
    } 
    
    class B { 
        public static $B = 'B'; 
    } 
    
    echo A::B(); // return 'B'