在PHP中为已经实例化的对象添加自定义函数?

Kir*_*met 2 php oop class function

在PHP中做这样的事情的最佳方法是什么?:

$a = new CustomClass();

$a->customFunction = function() {
    return 'Hello World';
}

echo $a->customFunction();
Run Code Online (Sandbox Code Playgroud)

(以上代码无效.)

gnu*_*nud 7

这是一个简单且有限的类似猴子补丁的PHP类.添加到类实例的方法必须将对象reference($this)作为其第一个参数python-style.此外,构造喜欢parentself不会工作.

OTOH,它允许您将任何回调类型修补到类中.

class Monkey {

    private $_overload = "";
    private static $_static = "";


    public function addMethod($name, $callback) {
        $this->_overload[$name] = $callback;
    }

    public function __call($name, $arguments) {
        if(isset($this->_overload[$name])) {
            array_unshift($arguments, $this);
            return call_user_func_array($this->_overload[$name], $arguments);
            /* alternatively, if you prefer an argument array instead of an argument list (in the function)
            return call_user_func($this->_overload[$name], $this, $arguments);
            */
        } else {
            throw new Exception("No registered method called ".__CLASS__."::".$name);
        }
    }

    /* static method calling only works in PHP 5.3.0 and later */
    public static function addStaticMethod($name, $callback) {
        $this->_static[$name] = $callback;
    }

    public static function __callStatic($name, $arguments) {
        if(isset($this->_static[$name])) {
            return call_user_func($this->_static[$name], $arguments);
            /* alternatively, if you prefer an argument list instead of an argument array (in the function)
            return call_user_func_array($this->_static[$name], $arguments);
            */
        } else {
            throw new Exception("No registered method called ".__CLASS__."::".$name);
        }
    }

}

/* note, defined outside the class */
function patch($this, $arg1, $arg2) {
    echo "Arguments $arg1 and $arg2\n";
}

$m = new Monkey();
$m->addMethod("patch", "patch");
$m->patch("one", "two");

/* any callback type works. This will apply `get_class_methods` to the $m object. Quite useless, but fun. */
$m->addMethod("inspect", "get_class_methods");
echo implode("\n", $m->inspect())."\n";
Run Code Online (Sandbox Code Playgroud)