我如何在这个类中调用
匿名函数在类外部可以正常工作(直接从manual复制)。
现在我明白了,
$greet
?我使用的是PHP 5.5.4。<?PHP
class Model
{
public $greet = function($name)
{
printf("Hello %s\r\n", $name);
};
}
$test = new Model();
$test->greet('World');
$test->greet('PHP');
?>
Parse error: syntax error, unexpected '$greet' (T_VARIABLE), expecting function (T_FUNCTION)
也尝试了这个,
$test = new Model();
call_user_func($test->greet('World'));
call_user_func($test->greet('PHP'))
匿名函数在类外部可以正常工作(直接从manual复制)。
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
编辑:我在我的调用中删除了美元符号(当答案开始出现时,我注意到了这一点)。这并没有帮助。
call_user_func($test->greet('World'));
call_user_func($test->greet('PHP'));
编辑:
class Model
{
public $greet;
function __construct()
{
$this->greet = function($name)
{
printf("Hello %s\r\n", $name);
};
}
}
$test = new Model();
$test->greet('johnny');
现在我明白了,
Fatal error: Call to undefined method Model::greet()
function
关键字意味着创建一个方法,而不是匿名函数。 - Arnold Daniels__call
方法将不再需要。目前PHP7处于alpha版本。我已经相应地更新了答案。 - Arnold Daniels