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

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

    There's a similar post on stackoverflow that clears out that this is only achievable through the implementation of certain design patterns.

    The only other way is through the use of classkit, an experimental php extension. (also in the post)

    Yes it is possible to add a method to a PHP class after it is defined. You want to use classkit, which is an "experimental" extension. It appears that this extension isn't enabled by default however, so it depends on if you can compile a custom PHP binary or load PHP DLLs if on windows (for instance Dreamhost does allow custom PHP binaries, and they're pretty easy to setup).

提交回复
热议问题