php - 如何向 PHP 中的现有类添加方法?

标签 php class extend inheritance

我将 WordPress 用作 CMS,我想扩展其中一个类而不必从另一个类继承;即我只是想向该类“添加”更多方法:

class A {

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

然后:

function insert_this_function_into_class_A() {
    echo 'b';
}

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

和:

A::insert_this_function_into_class_A();  # b

这在顽固的 PHP 中甚至可能吗?

最佳答案

如果你只需要访问类的公共(public)API,你可以使用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 的实例:

$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 更可行。

关于php - 如何向 PHP 中的现有类添加方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3011910/

相关文章:

symfony - FOS UserBundle -> 无法创建新用户

javascript - 将 JS 结果格式化为货币格式

javascript - 在 ajax 加载部分中不工作 jquery

javascript - 在 JavaScript 类方法中,即使使用箭头函数,也无法在 addEventListener() 内使用 'this'。如何解决这个问题

ios - 如何使用 Swift 类在数组中添加信息

javascript - 我可以使用原型(prototype) 'extend' jQuery 对象吗?

css - 将@extend 与父样式合并并创建一个类名

php - 使用 MySQL 和 PHP 计算某个日期期间的占用天数

PHP:从文本文件中获取接下来的n个字节

java - Java运行时如何获取变量声明的类型?