【发布时间】:2019-06-20 22:49:32
【问题描述】:
我正在尝试使用闭包编写类似 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()
【问题讨论】:
-
@hanshenrik Idk,这背后可能有与语言实现相关的原因......
-
作为一种解决方法,您可以创建它而不是 StdObject:
$cl = new class {public function __call($name,$args){return call_user_func_array($this->{$name},$args);}};- 现在您可以这样做$cl->sum = function ($a, $b) {return $a + $b;}; echo $cl->sum(33, 33);- 但这是个好主意吗?我不知道 -
我想这就是你要找的东西:stackoverflow.com/questions/4535330/…
-
@Nouphal.M 没有一个关于 4535330 的答案解释了为什么这些变通办法是必要的。很多答案都有很多不同的解决方法,但没有解释为什么普通的旧
$o=new StdClass;$o->f=function(){};$o->f();不起作用。