首页 > 解决方案 > 使用 PHP 中的扩展方法更改输出

问题描述

是否有可能在 PHP 中做这样的事情?

Image::myMethod(); // returns array
Image::myMethod()->toSring(); // Returns a string built inside the method toString

所以,换句话说,有没有办法让 PHP 检测该方法是否被另一个方法扩展,如果是,那么它返回self/this?

标签: phpoop

解决方案


编纂我在评论中的意思,这将在逻辑上为您提供相同的行为,尽管实现细节有所不同:

class Artifact extends ArrayObject {
    public function toString(): string {
        // custom stuff, use ArrayObject api to access underlying data
    }
}

class Image {
    public function myMethod(): Artifact {
        // generate your array data, then:
        return new Artifact($data);
    }
}

推荐阅读