在另一个类的变量中调用一个类的常量


Calling a class's constant in another class's variable

我想知道是否有任何可能性在PHP做以下;

<?php
class boo {
 static public $myVariable;
 public function __construct ($variable) {
   self::$myVariable = $variable;
 }
}
class foo {
  public $firstVar;
  public $secondVar;
  public $anotherClass;
 public function __construct($configArray) {
   $this->firstVar = $configArray['firstVal'];
   $this->secondVar= $configArray['secondVar'];
   $this->anotherClass= new boo($configArray['thirdVal']);
 }
}
$classFoo = new foo (array('firstVal'=>'1st Value', 'secondVar'=>'2nd Value', 'thirdVal'=>'Hello World',));
echo $classFoo->anotherClass::$myVariable;
?>

期望输出: Hello World

我得到以下错误;Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

我谷歌了一下,它与冒号(双点)$classFoo->anotherClass::$myVariable

我可不想费那么大的劲去换别的课。有办法解决这个问题吗?

提前感谢您的帮助。

注:我只是不想在这上面浪费几个小时来找到解决办法。昨天我已经花了2.5个小时更改了几乎整个Jquery,因为客户想要更改,今天早上我被要求收回更改,因为他们不想使用它(他们改变了主意)。

你需要做的是:

$anotherClass = $classFoo->anotherClass;
echo $anotherClass::$myVariable;

不支持将表达式展开为类名/对象用于静态调用/常量(但如上面所示,可以展开变量)。

如果你不关心内存和执行速度,这是正确的。
看来还是参考比较好:

$classRef = &$classFoo->anotherClass;
echo $classRef;