加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

在PHP中动态创建实例方法

发布时间:2020-12-13 13:14:19 所属栏目:PHP教程 来源:网络整理
导读:我希望能够在类的构造函数中动态创建实例方法,如下所示: class Foo{ function __construct() { $code = 'print hi;'; $sayHi = create_function( '',$code); print "$sayHi"; //prints lambda_2 print $sayHi(); // prints 'hi' $this-sayHi = $sayHi; }}$f
我希望能够在类的构造函数中动态创建实例方法,如下所示:
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

问题似乎是lambda_2函数对象没有在构造函数中绑定到$this.

任何帮助表示赞赏.

您正在为属性分配匿名函数,但然后尝试使用属性名称调用方法. PHP无法从属性中自动取消引用匿名函数.以下将有效
class Foo{

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

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

您可以利用magic __call方法拦截无效方法调用,以查看是否存在包含回调/匿名函数的属性,但:

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

从PHP5.3开始,您还可以创建Lambdas

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

有关详细参考,请参见PHP manual on Anonymous functions.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读