将方法作为参数发送给其他类构造函数并执行

时间:2019-07-02 19:21:35

标签: php oop constructor anonymous-function

我有两个班级AB

我想通过A构造函数将方法从B发送到B,然后在B中执行。我一直在尝试使用像这样的匿名函数:

    class A 
    {
        public function __construct()
        {
            // Send testMethod() to B with an anonymous function
            new B(function (string $test) {
                $this->testMethod($test);
            });
        }

        protected function testMethod(string $test) {
            echo ($test);
        }
    }


    class B 
    {
        protected $testFct;

        public function __construct($fctToExecute)
        {
            // Asign anonymous function to $testFct to be executed in all object
            $this->testFct= function (string $test) {
                $fctToExecute($test);
            };
        }

        // Want to be able now to call this $testFct function in a method like :
        protected function methodWhereICallTestfct() {
            $this->testFct("I'm dumb!"); // It has to echo "I'm dumb!"
        }        
    }

但是当我尝试设置它时,总是会收到类似以下错误:

Uncaught Error: Call to undefined method testFct()

您知道问题是什么吗?我想指定我的php版本为PHP 7.1.3

编辑:

Here是否有可能看到与我更相似的代码,从而返回错误

1 个答案:

答案 0 :(得分:1)

您的代码中有2个错误。

第一个错误是您忽略了$fctToExecute中的参数B::__construct()。如果要将传递的闭包保存到对象B的属性中,则不需要其他闭包。

public function __construct(closure $fctToExecute) {
    // Asign anonymous function to $testFct to be executed in all object
    $this->testFct = $fctToExecute;
}

第二个问题是,当您尝试执行闭包时,实际上是在尝试执行一个名为testFct的函数。您应该使用括号声明操作的优先级。

$this->testFct("I'm dumb!"); // This looks for a function called testFct

($this->testFct)("I'm dumb!"); // This will execute the closure stored in the property called $testFct

括号在这里有很大的不同。