PHP create_function结果存储为实例变量,并作为$object调用->;func()


PHP create_function result stored as instance variable, and called as $object->func()?

我使用PHPs create_function($args, $code)函数从数据库动态加载函数定义。

我尝试实现它的方式如下:

我有一个类MyClass,它有一个实例变量myFunction。构造函数使用对create_function的调用结果填充该实例变量。我希望为这个类的特定对象(一旦实例化(动态创建一个函数,它可以被称为$object->myFunction(arg1, arg2);

所以我的课看起来像:

class MyClass {
     public $myFunction = '';
     public function __construct() {
         $this->myFunction = //return function body from DB call.
     }

}

然后,我尝试在实例化的"MyClass"对象上从程序的其他地方调用这个动态函数,方法是。。。

$object = new MyClass();
$object->myFunction(args..); 

然而,我不断收到错误,例如:

MyClass and its behaviors do not have a method or closure named myFunction.

当我运行var_dump($object->myFunction)时,我会返回"lambda_xx",这是一个好迹象,意味着create_function至少在工作。


关于有效与无效案例的有趣更新

事实证明,在我的"其他文件"中,我正在做以下事情:

   $pm = Yii::app()->user->postMatching; //This is a PostMatching object made elsewhere
    $c = $pm->findRelated;
    foreach ($posts as $post) {
        var_dump($c);
        $postIds = $c($post, $limit);
        //post to related mapping
        $specificRelatedPostIds[$post->postId] = $postIds;
    }
    exit; // exiting for testing

这不起作用,但如果不是从Yii::app()->user->postMatching中提取对象$pm,而是创建一个新对象:

$pm = new PostMatching();
$c = $pm->findRelated; //the anon function instance variable
$c(); // THIS WORKS NOW!

因此,自然地,我在"新建"的情况和从Yii::app()->user->postMatching获得的情况下都对$pm$c进行了var_dump,它们是相同的。唯一不同的是匿名函数的名称(正如预期的那样(。

有人知道为什么会出现这种情况吗?在这两种情况下,$pm都是带有该实例变量的实例化PostMatching对象,我只是无法使用语法来调用它!


刚刚用新发现的"Twists"更新了上面的内容,谢谢大家!

也许沿着这条线的某些东西会很有用:

class MyClass {
     private $myFunction = '';
     public function __construct() {
         $this->myFunction = //return function body from DB call.
     }
     public function myFunction() {
         $args = func_get_args();
         return call_user_func_array($this->myFunction, $args);
     }
}

这是由于PHP存在解析相关的问题。这个版本应该工作:

$object = new MyClass();
$method = $object->myFunction;
$method(args..); 

在实际操作中查看

您可以这样调用方法:

call_user_func($object->myFunction, args..);