【问题标题】:how to change non static variable to static method in php如何在php中将非静态变量更改为静态方法
【发布时间】:2020-01-13 05:16:26
【问题描述】:

我像这样调用常量变量,但它显示错误,如何解决这个问题? 我不会像下面这些代码那样称呼它,

$b = new A()
$b::$test

这是我的代码

class A {
   const test = 4;
}

class B {

  private $a = null;
  public function __construct(){
      $this->$a = new A();
  }

  public function show(){
     echo $this->$a::test;
  }

}

$b = new B();
$b->show();

如何在 A 类中调用静态变量测试? 提前致谢

【问题讨论】:

  • 这能回答你的问题吗? Accessing PHP Class Constants。这不是变量,而是常数。
  • 我看到你已经回答了,但是想补充一点,尝试使用带有大写的常量变量,例如,const TEST

标签: php variables static non-static


【解决方案1】:

除了$this->$a::test;$this->$a = new A(); 之外,一切都很好。您必须使用没有$ 符号的属性,如下所示

class A {
   const test = 4;
}

class B {

  private $a = null;

  public function __construct()
  {
      $this->a = new A();
  }

  public function show()
  {
     echo $this->a::test;
  }
}

$b = new B();
$b->show();

【讨论】:

  • 嗨@Vibha Chosla 我正在用这个解决我的问题:$test = $this->a;回声 $test::test;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-17
相关资源
最近更新 更多