简体   繁体   English

从类内部调用全局变量函数的正确语法是什么?

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

I'm trying to call a global function from within a class. 我试图从一个类中调用全局函数。 The name of the function is contained in one of the public properties of the class. 函数的名称包含在该类的公共属性之一中。 I'm running into a small syntax problem that I have managed to work around, but I consider the work-around (an intermediary variable) inelegant and am looking for a more proper way to do this. 我遇到了一个很小的语法问题,设法解决了这个问题,但是我认为解决方法(中间变量)不太理想,并且正在寻找一种更合适的方法来解决此问题。

Consider the following code snippet: 考虑以下代码片段:

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 ();

I'm using the intermediary variable $theFuncName in bar() because directly referring to $this->theFuncName() implies that class Foo contains a method theFuncName , which is not the case. 我在bar()中使用中间变量$ theFuncName ,因为直接引用$ this-> theFuncName()意味着类Foo包含方法theFuncName ,情况并非如此。

What is the proper syntax to call the function referred to by the contents of $this->theFuncName without an intermediary variable? 在没有中间变量的情况下调用$ this-> theFuncName内容所引用的函数的正确语法是什么?

Use call_user_func() : 使用call_user_func()

class Foo 
{
    public $theFuncName = '';

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

For reference, see 供参考,请参阅

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

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