【问题标题】:Php extend method while overriding itPHP 扩展方法同时覆盖它
【发布时间】:2018-10-27 15:32:59
【问题描述】:

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

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 函数添加更多内容)

【问题讨论】:

  • 你为什么使用compact()
  • 没有理由,只是举例。类似于return view('view-file', compact($item))

标签: php function class methods


【解决方案1】:

如果您改用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);
    }

}

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

【讨论】:

  • 如果return 不仅返回 1 个变量?或者是与变量一起返回一些视图,比如return view('view-file', compact($item))。如果方法比我写的大,是否可以将Foo的编辑方法中的所有代码导入Bar类?
  • 您可以返回对象/视图等数组。主要是如何处理返回值。您可能会发现将其拆分为 2 种方法更容易,1 种方法组合数据,另一种方法返回视图。这允许您分离功能并以您需要的任何方式调用它。
  • 如果parent::edit() 正在返回来自return view('view-file', compact($item)) 的结果。你能告诉我如何将$item2 插入return view('view-file', compact($item, $item2))。我不知道如何分离parent::edit() 结果。
  • 我添加了一些新代码,试一试,看看它是否按您的需要工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 2023-03-04
相关资源
最近更新 更多