加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 16:49:30 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试为我正在处理的项目动态创建数据库实体泛化的基础.我基本上想要为任何扩展它的类中的属性动态创建一组标准方法和工具.就像使用 Python / Django免费获得的工具一样. 我从这个家伙那里得到了这个想法:http://www.stubbles.org/archives/65-Extendi
我正在尝试为我正在处理的项目动态创建数据库实体泛化的基础.我基本上想要为任何扩展它的类中的属性动态创建一组标准方法和工具.就像使用 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 &$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访问对象上下文.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读