Search code examples
phpyiianonymous-functionanonymous-methods

PHP create_function Instance variable - Unable to call anonymous function: Follow up


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!


Solution

  • 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.