php - 如何在 PHP 的类中使用匿名函数?

标签 php anonymous-function

如何调用 $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/

相关文章:

php - 我想在这种情况下在哪里有一个?

matlab - Matlab 中的多行匿名函数?

javascript - 为什么在 JavaScript 中有时需要 function()?

scala - 如何在链接部分函数时避免 `missing type` 错误

clojure - 为什么匿名函数定义语法存在差异?

php - 如果 mysql 选择查询返回空行,则设置默认值

php - 在 php 中的标准 Paypal 重定向页面上添加站点 Logo

javascript - 为什么这些 JavaScript 函数不添加到该对象中?

php - 根据主键将html表单连接到php页面

javascript - Magento 无法识别自定义 JavaScript 函数