【问题标题】:PHP: Using globally defined closure in a class method [duplicate]PHP:在类方法中使用全局定义的闭包[重复]
【发布时间】:2020-05-23 02:48:06
【问题描述】:

我有一个 global 变量的闭包,我想在我创建的类中运行它。但是,当我尝试以下代码时,我得到了错误,Exception: Call to undefined method TestClass::globalFunction()

这是我正在尝试的:

$globalFunction = function($var){
    echo "works $var";
};

class TestClass{
    private $globalFunction;
    function __construct(){
        $this->globalFunction = $GLOBALS['globalFunction'];
    }
    function testFunc(){
        $this->globalFunction('a');
    }
}
$arr = new TestClass();
$arr->testFunc();

【问题讨论】:

  • 这与它是全球性的并没有真正的关系。唯一的问题是调用它的语法。
  • 您是否考虑过为此使用特征?看起来它可能很合适。
  • 我以前没有见过特征。当然,这是一个有趣的选择。

标签: php class closures global


【解决方案1】:

因为$this->globalfunction 是一个变量,而不是一个方法,所以您需要将它用括号括起来以强制PHP 在尝试将$this->globalfunction 作为函数调用之前评估$this->globalfunction,即

function testFunc(){
    ($this->globalFunction)('a');
}

输出:

works a

Demo on 3v4l.org

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2014-06-15
    • 2012-10-10
    • 2018-12-08
    • 1970-01-01
    • 2013-01-04
    相关资源
    最近更新 更多