gpt4 book ai didi

php - 无法在 php 的 stdClass 属性中分配闭包

转载 作者:搜寻专家 更新时间:2023-10-31 21:47:39 25 4
gpt4 key购买 nike

我正在尝试使用闭包编写类似 js 的 php。但是,我不明白为什么我不能将闭包分配给 stdClass 属性。

代码 self 解释:

$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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com