如何向PHP中的现有类添加方法? [英] How to add a method to an existing class in PHP?

查看:428
本文介绍了如何向PHP中的现有类添加方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用WordPress作为CMS,我想扩展它的一个类,而不必继承另一个类;即我只是想添加更多的方法到该类:

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:

class A {

    function do_a() {
       echo 'a';
    }
}

那么:

function insert_this_function_into_class_A() {
    echo 'b';
}

(某种方式将后者插入A类)

(some way of inserting the latter into A class)

和:

A::insert_this_function_into_class_A();  # b

这是否可能在顽强的PHP?

Is this even possible in tenacious PHP?

推荐答案

如果只需要访问类的公共API,可以使用 Decorator

If you only need to access the Public API of the class, you can use a Decorator:

class SomeClassDecorator
{
    protected $_instance;

    public function myMethod() {
        return strtoupper( $this->_instance->someMethod() );
    }

    public function __construct(SomeClass $instance) {
        $this->_instance = $instance;
    }

    public function __call($method, $args) {
        return call_user_func_array(array($this->_instance, $method), $args);
    }

    public function __get($key) {
        return $this->_instance->$key;
    }

    public function __set($key, $val) {
        return $this->_instance->$key = $val;
    }

    // can implement additional (magic) methods here ...
}

然后包装SomeClass的实例:

Then wrap the instance of SomeClass:

$decorator = new SomeClassDecorator(new SomeClass);

$decorator->foo = 'bar';       // sets $foo in SomeClass instance
echo $decorator->foo;          // returns 'bar'
echo $decorator->someMethod(); // forwards call to SomeClass instance
echo $decorator->myMethod();   // calls my custom methods in Decorator



如果您需要访问 protected API,你必须使用继承。如果你需要访问 private API,你必须修改类文件。虽然继承方法很好,修改类文件可能会让你在更新时遇到麻烦(你会丢失任何补丁)。但两者比使用runkit更可行。

If you need to have access to the protected API, you have to use inheritance. If you need to access the private API, you have to modify the class files. While the inheritance approach is fine, modifiying the class files might get you into trouble when updating (you will lose any patches made). But both is more feasible than using runkit.

这篇关于如何向PHP中的现有类添加方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆