PHP扩展方法而覆盖它

时间:2018-10-27 15:32:59

标签: php function class methods

是否可以在覆盖父类的同时扩展方法?例如:

class Foo {

    public function edit() {
     $item = [1,2];
     return compact($item);
    }
}

class Bar extends Foo {
    public function edit() {
     // !!! Here, is there any way I could import $item from parent class Foo?
     $item2 = [3,4]; //Here, I added (extended the method with) some more variables
     return compact($item, $item2); // Here I override the return of the parent method.
    }
}

问题是我无法以任何方式编辑Foo类,因为它是供应商软件包。

我不想编辑需要扩展它们的供应商方法(向其return函数添加更多内容)

1 个答案:

答案 0 :(得分:2)

如果您改用array_merge(),则可能会更好地显示结果...

class Foo {

    public function edit() {
        $item = [1,2];
        return $item;
    }
}

class Bar extends Foo {
    public function edit() {
        $item = parent::edit();  // Call parent method and store returned value
        $item2 = [3,4]; //Here, I added (extended the method with) some more variables
        return array_merge($item, $item2); // Here I override the return of the parent method.
    }
}

$a = new Bar();
print_r($a->edit());

这将输出-

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

因此,对parent::edit()的调用将返回父类的数组,并将其从第二个类函数添加到数组中。

更新

我无法对此进行测试,但希望这能给您带来什么...

class Foo {
    protected function getData() {
        return [1,2];
    }
    public function edit() {
        return return view('view-file', compact($this->getData()));
    }
}

class Bar extends Foo {
    protected function getData() {
        $item = parent::edit();
        $item2 = [3,4];
        return array_merge($item, $item2);
    }

}

这意味着创建视图的唯一时间是在基类中,您要做的就是在派生类中添加额外的信息。

相关问题