从 class 中调用全局变量函数的正确语法是什么?

What is the proper syntax to call a global variable function from within a class?

我正在尝试从 class 中调用全局函数。该函数的名称包含在 class 的 public 属性之一中。我 运行 遇到了一个我设法解决的小语法问题,但我认为解决方法(一个中间变量)不够优雅,我正在寻找更合适的方法来解决这个问题。

考虑以下代码片段:

class Foo {

  public $theFuncName = '';

  public function bar () {
    if ($this->theFuncName != '') {
      $theFuncName = $this->theFuncName;
      $theFuncName ();
    }
  }

}

function myGlobalFunc () {
  echo "This is myGlobalFunc\n";
}

$foo = new Foo ();
$foo->theFuncName = 'myGlobalFunc';
$foo->bar ();

我在 bar() 中使用中间变量 $theFuncName 因为直接引用 $this- >theFuncName() 意味着 class Foo 包含一个方法 theFuncName,事实并非如此。

在没有中间变量的情况下调用 $this->theFuncName 的内容引用的函数的正确语法是什么?

使用call_user_func():

class Foo 
{
    public $theFuncName = '';

    public function bar () 
    {
        if (is_callable($this->theFuncName)) {
            call_user_func($this->theFuncName);
        }
    }
}

有关参考,请参阅