Is class extension practice good?
Well, yes, if you do it right and for the right reason.
The concept of inheritance (class extension) in object-oriented programming works the same way as if you had these objects in the real world.
In the real world, when you use the Car world, then by convention you usually mean all cars, and you consider the common attributes in it, such as wheels, engine, steering, throttle, brake, etc. but there are some cars that have these attributes and some additional ones, for example, a fire truck car also has some additional attributes as an attached ladder, some tubes for throwing water, etc. The same could be taken into account for the “behavior” of certain objects, for example, a car can move, and we mean that you have a turn of the wheels on the road to move (using the car’s movement method). In addition, the firefighter may have enhanced behavior, for example, may move up and down the stairs that he has. This can be modeled using the moveLadder () method in the FireTruckCar class.
If you want to represent these concepts in PHP (OOP) classes, you can do:
class Car {
protected $wheels; protected $engine; //Rest attributes of Car. public function __construct($wheels, $engine) { $this->wheels = $wheels; $this->engine = $engine; //Initialize more attributes. } function move(){ $this->wheels->rotate(); } //.....
}
FireTruckCar class extends car {
//Additional Attributes. //The attributes of Car class belong to this //one too and are accessible as private. protected $ladder; protected $tubes; public function __construct($wheels, $engine, $ladder, $tubes) { //Call the parent constructor, to initialize parent attributes parent::__construct($wheels, $engine); $this->ladder = $ladder; $this->tubes = $tubes; } function moveLadder($direction){ $this->ladder->move($direction); } //...
}
Of course, there are many additional concepts in inheritance and in general OOP, such as method overload / override, abstract classification, etc., but I am not going to explain them here, since the point will be missed. I suggest you look for the Object-Oriented Programming Principles, although they are well aware of them.