如何将函数作为param传递给一个类,然后将其赋给本地类的var!
这是我的场景,能解决吗?
<?php
class a {
protected $var;
function __construct($fun) {
echo $fun('world'); // This is working perfect
$this->var = $fun;
}
function checkit($x) {
return $this->var($x); // This is not working [ Call to undefined method a::var() ]
}
}
$mth = 'mathm';
$cls = new a(&$mth); // result [ hello (world) ]
echo $cls->checkit('universe'); // <- not working as it fail
function mathm($i) {
return 'hello (' . $i . ')';
}
?>发布于 2012-12-14 03:11:44
return $this-var($x);需要满足以下条件:
return $this->var($x);发布于 2012-12-17 23:00:05
我认为你在这里搞混了什么。在您的代码中,您只将变量的地址(包含字符串"mathm“作为其值)传递给class a的构造函数。引用被保存到实例变量$var (仍然是一个字符串值)。然后在你的checkit()中,你尝试使用这个值('mathm'),就好像它是一个函数一样。函数mathm()确实存在,但不在class a的作用域中。所以class a对任何名为mathm的函数的位置一无所知。这样就产生了错误。
如果在checkit()中插入代码行print_r($this->var);,您将看到输出是一个简单的字符串,而不是函数或对函数的引用。
你可以使用闭包或者匿名函数来传递函数。或者,您可以创建一个包含函数mathm的类,然后传递此类类的一个实例以在类a中使用。
我希望这能帮到你!
https://stackoverflow.com/questions/13866717
复制相似问题