如何在 PHP 的构造函数类中添加方法?

比兹麦

我有一个class A,如果它的一个参数被设置到需要一种新的方法true

A级

Class A{

   private $is_new_method;  

   public function __construct( $is_new_method = false, $new_method_name = "" ){

        $this->is_new_method = $is_new_method;

        if( $this->is_new_method ){
           //TODO : add new method in this class based on $new_method_name 
        }      
   }

}

我看到了runkit_method_add但它需要(PECL runkit >= 0.7.0)。

注意:此函数将在框架的核心内调用,如下所示:

$foo = new A();
$foo->myNewFunction();

那么最好的方法是什么?

比兹麦

谢谢@Jared Farrish!我根据您的建议找到了我的解决方案。

Class A{

    private $is_new_method; 

    private $new_method; 

    public function __construct( $is_new_method = false, $new_method_name = "" ){

        $this->is_new_method = $is_new_method;

        if( $this->is_new_method ){
           $new_method = $this->make_my_new_method( $new_method_name ); 
        }      
   }

   private function make_my_new_method( $method_name ){
        $functionName  = "foo_" . $method_name;
        $$functionName = function ( $item ) {
            print_r( $item );
        }
        return $$functionName;
   }

   public function __call( $method, $args){
       if ( isset( $this->new_method ) ) {
           $func = $this->new_method;
           return call_user_func_array( $func, $args );
       }
   }

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章