简体   繁体   中英

PHP class property contains child of a parent but was shown error due to parent class not containing method from child

I am learning OOP right now and I have a property that specifies what class it should be.

class Controller{
  public ?Model $model;
}

class LoginModel extends Model{
  public function login(){}
}

Now, I want to load a class that is an inheritance of Model but contains a unique method not from Model. That causes the lint to think that there is an error in the code. Is there a way to fix the issue from Controller->model?

$controller = new Controller();
$controller->model = new LoginModel();
echo $controller->model->login();

I know that one way is we can change Model to LoginModel but that would be tedious if there are a lot of different controllers with different model designed to do different things.

consider this example

class Controller
{
    public ?Model $model;
}

class Model { }

class LoginModel extends Model
{
    public function login() { }
}

class LogoutModel extends Model { }


$controller = new Controller();

$controller->model = new LoginModel();
$controller->model->login(); //This works 

$controller->model = new LogoutModel();
$controller->model->login(); //This doesn't works

The lint is saying that you cannot assure that there will be a login() to call. So unless you'll have a login() method in all models, in which case you can define an abstract or interface, otherwise since it can fail it will show you the error.

PS: there is a way around it, but I wouldn't recommend it for regular use.

if($controller->model instanceof LoginModel) 
{
    $controller->model->login(); //This works
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM