实现接口的抽象类的方法重写

时间:2017-06-07 16:43:22

标签: php laravel

我的问题可能有点蹩脚。我无法真正理解抽象类方法覆盖是如何工作的。在下面的代码中,我有OrderController方法,它接受从Model类本身派生的Order模型,为什么会抛出错误?

interface CrudInterface
{
    public function show(Model $model);
}

abstract class CrudController extends Controller implements CrudInterface {
    public function show(Model $model)
    {
        return $model;
    }
}

class OrderController extends CrudController {

    // Throws an erorr ("
    // Declaration of App\Http\Controllers\OrderController::show(App\Order $order) should be compatible with 
    // App\Http\Controllers\CrudController::show(Illuminate\Database\Eloquent\Model $model
    // ")
    public function show (Order $order) {
        return $order
    }

}

提前致谢。

1 个答案:

答案 0 :(得分:3)

接口应匹配:

class OrderController extends CrudController {

    public function show (Model $order) {
        if (!$order instanceOf Order) {
           throw new InvalidArgumentException();
        }
        return $order
    }
}