繁体   English   中英

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

[英]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

我用Google搜索,它与$classFoo->anotherClass::$myVariable 冒号(双点) $classFoo->anotherClass::$myVariable

我不想麻烦改变我的其他课程。 反正这个问题呢?

提前谢谢你的帮助。

PS我只是不想在这方面浪费几个小时才找到方法。 我已经花了2.5个小时来改变几乎整个Jquery,因为客户想要改变,今天早上我被要求接受更改,因为他们不想使用它(他们改变主意)。 我现在只是想避免重大改变。

你需要这样做:

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

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

如果您不关心内存和执行速度,这是正确的。
似乎参考会更好:

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

适合我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM