将函数分配给PHP中的类变量[duplicate]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我可以在PHP中为类变量分配一个函数,即$this->variable

但是,当我尝试执行该函数时,它失败了:

FATAL ERROR Call to undefined method a::f()

这是一个说明问题的片段:

<?php

new a();

class a
{
    private $f;
    function __construct()
    {
        $g = function() { echo "hello g"; };
        $g(); //works

        $this->f = function() { echo "hello f"; };
        $this->f();  //FATAL ERROR Call to undefined method a::f()
    }
}
php php-7 anonymous-function php-5.6 php-5.4
1个回答
0
投票

看起来语法混淆了PHP。

将函数分配回局部变量,一切都很好!

<?php

new a();

class a
{
    private $f;
    function __construct()
    {
        $g = function() { echo "hello g"; };
        $g();

        $this->f = function() { echo "hello f"; };
        $f = $this->f;   //ASSIGN TO LOCAL VARIABLE!!!
        $f();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.