我试图使用闭包编写类似 js 的 php。但是,我不明白为什么我不能为 stdClass 属性分配一个闭包。

代码解释了自己:

$sum = function ($a, $b) {return $a + $b;};
echo $sum(11, 11);
// prints 22



$arr = [];
$arr['sum'] = function ($a, $b) {return $a + $b;};
echo $arr['sum'](22, 22);
// prints 44



$cl = new stdClass;
$cl->sum = function ($a, $b) {return $a + $b;};
echo $cl->sum(33, 33);
// Fatal error: Uncaught Error: Call to undefined method stdClass::sum()



# although I can't think of any use cases for this
class Custom {
    public $sum = NULL;

    function __construc() {
        $this->sum = function ($a, $b) {return $a + $b;};
    }
}

$custom = new Custom;
echo $custom->sum(44, 44);
// Fatal error: Uncaught Error: Call to undefined method Custom::sum()

最佳答案

只需将属性名称括在圆括号中即可。

echo ($cl->sum)(33, 33);
echo ($custom->sum)(44, 44);

来自 3v4l 的示例:

https://3v4l.org/3ZqNV

根据评论编辑:

Javascript 中的对象只能有属性。此属性可以是原始值、其他对象或函数,但属性的名称是唯一的,尽管其内容。

在 PHP 中,一个对象可以同时具有属性和方法。

假设我们有以下代码:
class MyClass
{

    public $foo;

    public function __construct()
    {
        $this->foo = function(int $a, int $b): int {
            return $a * $b;
        };
    }

    public function foo(int $a, int $b): int
    {
        return $a + $b;
    }
}

$myClass = new MyClass();

echo $myClass->foo(2, 3);

属性 foo 和方法 foo 都具有相同的签名,但程序员的意愿是什么?

此代码将调用方法 foo 并打印 5,因此任何 $var->name() 行都被解释为方法调用。

如果你想在属性内部调用闭包,你必须使用不同的语法,以便没有歧义。
echo ($myClass->foo)(2, 3) //Prints 6

https://3v4l.org/PXiMQ

关于php - 无法在 php 的 stdClass 属性中分配闭包,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54393444/

10-12 07:03