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

查看:45
本文介绍了如何向 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?

推荐答案

如果你只需要访问类的Public API,你可以使用一个装饰器:

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天全站免登陆