Pedram marandi
Pedram marandi

Reputation: 1614

error in abstract should be compatible with

I have abstract class something like this

protected function update(Request $request, $id)
{
    //function body
}

and extended class like

protected function update(PageRequest $request, $id)
{
    //function body
}

injected PageRequest extended from Request

<?php

namespace App\Http\Requests;

use App\Helpers\Helpers;
use App\Http\Requests\Request;

class PageRequest extends Request
{
    //function body
}

I get this error

Declaration of App\Http\Controllers\PagesController::update() should be compatible with App\Http\Controllers\MasterController\CrudController::update(App\Http\Requests\Request $request, $id)

I know to pass all of the arguments and access same for update() methods and I think I do it correctly.

Upvotes: 3

Views: 1428

Answers (2)

axiac
axiac

Reputation: 72216

The best solution is to use an interface, as explained in this answer.

Another solution is to declare the method update() in the child class without changing its signature and verify in the code that the argument has the correct type.

Something like this:

protected function update(Request $request, $id)
{
    if (! $request instanceof PageRequest) {
        throw new \InvalidArgumentException('Unexpected type ('.get_class($request).') of argument $request. Expecting an object of type PageRequest.');
    }

    // Do whatever you need to do with $request here
    // It is an object of type PageRequest
}

This solution has its own advantages in some contexts but it makes the code more verbose and adds extra code to run.

Upvotes: 1

Med
Med

Reputation: 2063

Correct way to do this:

class Request implements RequestInterface
class PageRequest extends Request

And the function :

protected function update(RequestInterface $request, $id)

Upvotes: 4

Related Questions