【问题标题】:PHP - call to a variable static method using the scope resolution operatorPHP - 使用范围解析运算符调用变量静态方法
【发布时间】:2015-09-14 23:15:31
【问题描述】:

我想以类名和方法名都是变量的方式调用静态方法。

例子:

class QQQ {
   public function www($x) {
      echo $x;
   }
}

$q = 'QQQ';
$w = 'www';

$q::$w(7); // this is what I am trying to do but it throws an error.

想法?

【问题讨论】:

  • 你没有定义$x,所以报错
  • 我放了一些东西而不是 $x,同样的错误。
  • 你的方法不是静态的
  • 它会抛出什么样的错误?
  • 函数名必须是字符串...

标签: php scope-resolution


【解决方案1】:

只需要改变

public function www($x) {

public static function www($x) {

因为您是通过范围解析运算符:: 调用它,所以它应该是静态的或者您应该更改调用它的方式

$test = new $q;

$test->$w(5);

应该可以工作,这取决于你想用它做什么。

【讨论】:

  • 您能解释一下原因吗?直接调用 QQQ::foo(7) 就可以了。但是调用它 $q::$w(7) 表示函数名必须是字符串
猜你喜欢
  • 2011-10-24
  • 2016-07-23
  • 2015-11-10
  • 2016-04-09
  • 2014-03-23
  • 2013-06-13
  • 1970-01-01
  • 2020-12-12
  • 1970-01-01
相关资源
最近更新 更多