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 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3