Victordb
Victordb

Reputation: 549

Php extend method while overriding it

Is it possible to extend a parent class method while overriding it ? For example:

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.
    }
}

The issue is that I cannot edit the Foo class in any way as it is a vendor package.

I don't want to edit the vendor methods I need to extend them (add something more to their return function)

Upvotes: 0

Views: 292

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

If you used array_merge() instead it will probably show the results better...

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());

This will output -

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

So the call to parent::edit() will return the array from the parent class and this will be added to the array from the second class function.

Update:

I can't test this, but hopefully this will give you what your after...

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);
    }

}

This means that the only time you create the view is in the base class, all you do is add the extra information in the derived class.

Upvotes: 2

Related Questions