Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从类中调用全局变量函数的正确语法是什么?_Php_Function_Class_Syntax_Global - Fatal编程技术网

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

Php 从类中调用全局变量函数的正确语法是什么?,php,function,class,syntax,global,Php,Function,Class,Syntax,Global,我试图从类中调用一个全局函数。函数名包含在类的一个公共属性中。我遇到了一个我已经解决的小语法问题,但是我认为周围的工作(中间变量)不优雅,我在寻找一个更合适的方法来做这件事。 考虑以下代码段: class Foo { public $theFuncName = ''; public function bar () { if ($this->theFuncName != '') { $theFuncName = $this->theFuncName;

我试图从类中调用一个全局函数。函数名包含在类的一个公共属性中。我遇到了一个我已经解决的小语法问题,但是我认为周围的工作(中间变量)不优雅,我在寻找一个更合适的方法来做这件事。 考虑以下代码段:

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()意味着类Foo包含一个方法theFuncName,但事实并非如此

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

使用
call\u user\u func()

有关参考,请参阅


封装的目的是什么?为什么不直接调用
myGlobalFunc()
class Foo 
{
    public $theFuncName = '';

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