duanbeng6709 2011-10-28 22:40
浏览 60
已采纳

PHP create_function实例变量 - 无法调用匿名函数:跟进

This is somewhat a follow up to a previous question - but I've distilled the question down and have the "works" vs. "doesn't work" cases narrowed down much more precisely.

My Goal: I have a class MyClass that has an instance variable myFunction. Upon creating a MyClass object (instantiating), the constructor assigns the instance variable myFunction with the result of a call to create_function (where the code and args come from a db call).

Once this object of type MyClass is created (and stored as an instance variable of another class elsewhere) I want to be able to call myFunction (the instance variable anonymous function) from "anywhere" that I have the MyClass object.


Experimental Cases -- below is my highly simplified test code to illustrate what works vs. what doesn't (i.e. when the expected functionality breaks)

class MyClass extends AnotherClass {

     public $myFunction;

     function __construct() {

         $functionCode = 'echo "NyanNyanNyan";';

         $this->myFunction();

         /*Now the following code works as expected if put in here for testing*/
         $anonFunc = $this->myFunction;
         $anonFunc();   //This call works just fine (echos to page)!   

         /*And if i make this call, it works too! */
         self::TestCallAnon();       

     }

     public function TestCallAnon() {

          $anonFunc2 = $this->myFunction;
          $anonFunc2();
     }

}

However, if I do the following (in another file, it errors saying undefined function () in... within the Apache error log.

//I'm using Yii framework, and this is getting the user 
//objects instance variable 'myClass'. 

$object = Yii::app()->user->myClass; 

$object->TestCallAnon(); // **FAILS**

or

$func = $object->myFunction;
$func(); // ** ALSO FAILS **

In addition, several variations of calls to call_user_func and call_user_func_array don't work.

If anyone is able to offer any insight or help that would be great :).

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • dqgxazo4483 2011-10-31 00:39
    关注

    I ended up solving this issue via a workaround that ended up being a better choice anyways.

    In the end I ended up having a static class that had a method to randomly return one of the possible identifiers, and then another method which accepted that identifier to build the anonymous function upon each class.

    Slightly less elegant than I would like but it ends up working well.

    Thanks to everyone for your efforts.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址