Reputation: 19
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.
Upvotes: 1
Views: 48
Reputation: 1134
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
}
Upvotes: 1