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条)

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示