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

后端 未结 9 2266
星月不相逢
星月不相逢 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:39

    With PHP 7 you can use anonymous classes, which eliminates the stdClass limitation.

    $myObject = new class {
        public function myFunction(){}
    };
    
    $myObject->myFunction();
    

    PHP RFC: Anonymous Classes

提交回复
热议问题