php – 调用运行时创建的函数

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 调用运行时创建的函数脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试为我正在处理的项目动态创建数据库实体泛化的基础.我基本上想要为任何扩展它的类中的属性动态创建一组标准方法和工具.就像使用 Python / Django免费获得的工具一样.

我从这个家伙那里得到了这个想法: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 &amp;$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中建议的解决方案不适用于此.

在这里很难过…还有其他建议吗?

更新

编辑简洁.

解决方法

尝试这样(你必须使你需要的变量可用于该方法)

$this->$methodName = function() use ($this,$name){ 
    echo "<br>".$methodName." is called";
    return $this->$$name; 
};

应该通过$this访问对象上下文.

脚本宝典总结

以上是脚本宝典为你收集整理的php – 调用运行时创建的函数全部内容,希望文章能够帮你解决php – 调用运行时创建的函数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。