How to add a new method to a php object on the fly?

后端 未结 9 2258
星月不相逢
星月不相逢 2020-11-28 04:03

How do I add a new method to an object \"on the fly\"?

$me= new stdClass;
$me->doSomething=function ()
 {
    echo \'I\\\'ve done something\';
 };
$me->         


        
9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 04:20

    you can also save functions in an array:

    arrayFuncs[$name] = $function;
        }
        //
        public function callFunc($namefunc,$params=false){
            if(!isset($this->arrayFuncs[$namefunc])){
                return 'no function exist';
            }
            if(is_callable($this->arrayFuncs[$namefunc])){
                return call_user_func($this->arrayFuncs[$namefunc],$params);
            }
        }
    
    }
    $foo = new Foo();
    
    //Save function on array variable with params
    $foo->addFunc('my_function_call',function($params){
        return array('data1'=>$params['num1'],'data2'=>'qwerty','action'=>'add');
    });
    //Save function on array variable
    $foo->addFunc('my_function_call2',function(){
        return 'a simple function';
    });
    //call func 1
    $data = $foo->callFunc('my_function_call',array('num1'=>1224343545));
    var_dump($data);
    //call func 2
    $data = $foo->callFunc('my_function_call2');
    var_dump($data);
    ?>
    

提交回复
热议问题