I’m new to OO programming, and I’m trying to understand how to assign values to common properties from subclasses in a proper manner. I always end up doing it in different ways every time, so I thought it would be a good idea to ask you how you normally do.
Let’s say that I have a parent class, Fruit ,and two subclasses Apple and Banana.
abstract class Fruit {
protected $color; //empty property
protected function getColor(){
return $this->color;
}
}
class Apple extends Fruit {
protected $color = 'red';
}
class Banana extends Fruit {
protected $color = 'yellow';
}
?>
Each subclass MUST have the property color, which will be used by, let’s say, the function getColor in the superclass.
But how do I deal with the property?
-
I define the empty variable $color in the parent. Then I set the variable $color in the subclasses, and pass them to the parent by parent::__construct, to assign the value to the property in the parent.
-
I define the empty variable $color in the parent. Then I simply use $this->color in the subclass to set the value.
-
I define the property in each subclass, and leave it like that. The inherited methods can still use it.
I’d like to think that it’s best to collect the common properties in the parent class, but it just feels like overkill to write that many lines to set a few values (and if I have lots of properties, there will be lots of function parameters as well). Number two and three works, but it is hard to see that I actually need to define the property at all.
How should I think here? I’m so confused by all the OO way of thinking that I barely write any code at all, haha.
Thank you.
There is no “silver bullet”. In general, all the fields that are expected to be different in subclasses should be set through the parameters of the constructor to ensure that they are explicitly set. Other fields can be initialized by assigning values to the properties.
For example, the color of a fruit can be set by assigning value to the property (because many fruits can be red), but the name should be set by constructor’s parameter (because the name uniquely identifies the fruit).