douju8113 2018-03-03 19:44
浏览 50
已采纳

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

I have a class A which needs a new method if one of its arguments is set up to true.

Class 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 
        }      
   }

}

I saw runkit_method_add but it needs (PECL runkit >= 0.7.0).

Notice: this function will be call inside a core of a framework like this :

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

So what is the best way to do this ?

  • 写回答

2条回答 默认 最新

  • dongsong1911 2018-03-03 20:30
    关注

    Thanks @Jared Farrish ! I found my solution based on your recommandation.

    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 );
           }
       }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询
  • ¥15 R语言建立随机森林模型出现的问题
  • ¥20 unity内置语言切换的按钮设置
  • ¥15 中级微观经济学,生产可能性边界问题
  • ¥15 TCP传输时不同网卡传输用时差异过大
  • ¥15 请各位看看我写的属于什么算法,或者有更正确的写法?
  • ¥15 html5 qrcode 扫描器
  • ¥15 爬取网页信息并保存需要完整代码