2016-09-29 166 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'