如何调用 $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()
最佳答案
您调用 greet
的事实使 PHP 将其视为函数而不是属性。您可以在 PHP 中为属性和方法使用相同的名称,因此区别是相关的。
PHP 7+
在 PHP7 中,__call()
不再需要方法来调用绑定(bind)到属性的闭包,因为 Uniform Variable Syntax .这将允许您在任何代码周围添加括号,就像在算术中一样。
class Model
{
public $greet;
function __construct()
{
$this->greet = function($name)
{
printf("Hello %s\r\n", $name);
};
}
}
$test = new Model();
($test->greet)('johnny');
PHP 5作为解决方法,您可以使用
__call()
魔术方法。它将捕获对未定义 greet
的调用方法。class Model
{
public $greet;
function __construct()
{
$this->greet = function($name)
{
printf("Hello %s\r\n", $name);
};
}
function __call($method, $args)
{
if (isset($this->$method) && $this->$method instanceof \Closure) {
return call_user_func_array($this->$method, $args);
}
trigger_error("Call to undefined method " . get_called_class() . '::' . $method, E_USER_ERROR);
}
}
$test = new Model();
$test->greet('johnny');
关于php - 如何在 PHP 的类中使用匿名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30853525/