How to add a method to an existing class in PHP?

后端 未结 5 1275
情深已故
情深已故 2020-12-05 04:58

I\'m using WordPress as a CMS, and I want to extend one of its classes without having to inherit from another class; i.e. I simply want to \"add\" more methods to that class

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 05:35

    An updated way for 2014 that copes with scope.

    public function __call($method, $arguments) {
        return call_user_func_array(Closure::bind($this->$method, $this, get_called_class()), $arguments);
    }
    

    Eg:

    class stdObject {
        public function __call($method, $arguments) {
            return call_user_func_array(Closure::bind($this->$method, $this, get_called_class()), $arguments);
        }
    }
    
    $obj = new stdObject();
    $obj->test = function() {
        echo "
    " . print_r($this, true) . "
    "; }; $obj->test();

提交回复
热议问题