Dynamically Create Instance Method in PHP

自闭症网瘾萝莉.ら 提交于 2019-12-18 03:40:30

问题


I'd like to be able to dynamically create an instance method within a class' constructor like so:

class Foo{
   function __construct() {
      $code = 'print hi;';
      $sayHi = create_function( '', $code);
      print "$sayHi"; //prints lambda_2
      print $sayHi(); // prints 'hi'
      $this->sayHi = $sayHi; 
    }
}

$f = new Foo;
$f->sayHi(); //Fatal error: Call to undefined method Foo::sayHi() in /export/home/web/private/htdocs/staff/cohenaa/dev-drupal-2/sites/all/modules/devel/devel.module(1086) : eval()'d code on line 12 

The problem seems to be that the lambda_2 function object is not getting bound to $this within the constructor.

Any help is appreciated.


回答1:


You are assigning the anonymous function to a property, but then try to call a method with the property name. PHP cannot automatically dereference the anonymous function from the property. The following will work

class Foo{

   function __construct() {
      $this->sayHi = create_function( '', 'print "hi";'); 
    }
}

$foo = new Foo;
$fn = $foo->sayHi;
$fn(); // hi

You can utilize the magic __call method to intercept invalid method calls to see if there is a property holding a callback/anonymous function though:

class Foo{

   public function __construct()
   {
      $this->sayHi = create_function( '', 'print "hi";'); 
   }
   public function __call($method, $args)
   {
       if(property_exists($this, $method)) {
           if(is_callable($this->$method)) {
               return call_user_func_array($this->$method, $args);
           }
       }
   }
}

$foo = new Foo;
$foo->sayHi(); // hi

As of PHP5.3, you can also create Lambdas with

$lambda = function() { return TRUE; };

See the PHP manual on Anonymous functions for further reference.




回答2:


You can use the __call magic method to employ run-time instance methods.

class Foo
{
    public function __call($name, $args) 
    {
        if ($name == 'myFunc') {
            // call myFunc
        }
    }
}


来源:https://stackoverflow.com/questions/3231365/dynamically-create-instance-method-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!