脚本宝典收集整理的这篇文章主要介绍了php – 调用运行时创建的函数,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我从这个家伙那里得到了这个想法:http://www.stubbles.org/archives/65-Extending-objects-with-new-methods-at-runtime.html
所以我已经实现了__call函数,如上面的帖子所述,
public function __call($method,$args) { echo "<br>Calling ".$method; if (isset($this->$method) === true) { $func = $this->$method; $func(); } }
我有一个函数,通过get_object_VARs给我对象public / PRotected属性,
public function getJsonData() { $var = get_object_vars($this); foreach($var as &$value) { if (is_object($value) && method_exists($value,'getJsonData')) { $value = $value->getJsonData; } } return $var; }
现在我想为它们创建一些方法:
public function __construct() { foreach($this->getJsonData() as $name => $value) { // Create standard getter $methodName = "get".$name; $me = $this; $this->$methodName = function() use ($me,$methodName,$name) { echo "<br>".$methodName." is called"; return $me->$name; }; } }
感谢Louis H.在下面指出了“use”关键字.
这基本上可以动态创建一个匿名函数.该函数是可调用的,但它不再位于其对象的上下文中.它产生“致命错误:无法访问受保护的属性”
不幸的是,我已经绑定了PHP版本5.3,它排除了Closure :: bind.因此,Lazy loading class methods in PHP中建议的解决方案不适用于此.
我在这里很难过…还有其他建议吗?
更新
编辑简洁.
以上是脚本宝典为你收集整理的php – 调用运行时创建的函数全部内容,希望文章能够帮你解决php – 调用运行时创建的函数所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。