这个问题在这里已有答案:
我可以在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
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();
}
}