【发布时间】:2016-04-13 17:09:33
【问题描述】:
我正在尝试做类似于PHP anonymous function assigned to class property in constructor is always null? 的事情,但我的解决方案似乎更简单。我想从 Stack Overflow Hot Shots 获得有关此解决方案的 cmets 以及是否有更好的解决方案。这是一个“最佳实践”的问题。
我想将一个函数(匿名或已定义)传递给一个类/对象,并能够稍后调用该函数。我从这个开始:
function Foo($arg) {return sprintf('In Foo(%s)',$arg);}
function Bar($arg) {return sprintf('In Bar(%s)',$arg);}
class TestIt {
private $func;
public function __construct( $func ) { $this->func = $func; }
public function OutPut($arg) {
return $this->func($arg);
}
}
$test = new TestIt('Foo');
echo $test->OutPut('Bozo');
运行时,我收到一个错误,指出方法 $this->func 不存在。如果我在方法OutPut() 中放置is_callable 测试,我发现$this->func 实际上是可调用的,但错误仍然存在。
但是,如果我使用 is_callable 的第三个参数,我可以正常工作。
public function OutPut($arg) {
return is_callable($this->func,false,$tmpfunc) ? $tmpfunc($arg) : null;
}
这如何作为解决方案叠加起来?很好奇你的想法。
【问题讨论】:
-
__construnt只是您的问题中的错字还是您的代码中也有?