Object composition and abstraction are fundamental concepts in PHP object-oriented programming (OOP).
Object Composition:
Object composition is a technique where an object is made up of one or more other objects. This allows for:
Code reuse
Easier maintenance
More flexibility
In PHP, object composition is achieved by including one class within another using a property or method.
Abstraction:
Abstraction is the concept of showing only the necessary information to the outside world while hiding the internal details. In PHP, abstraction is achieved using:
Abstract classes
Interfaces
Encapsulation (access modifiers)
Abstraction helps to:
Reduce complexity
Improve code organization
Increase flexibility
An example of object composition and abstraction in PHP is:
// Abstraction
abstract class Vehicle {
abstract public function move();
}
// Object Composition
class Car {
private $engine;
public function __construct(Engine $engine) {
$this->engine = $engine;
}
public function move() {
$this->engine->start();
echo “Car is moving”;
}
}
class Engine {
public function start() {
echo “Engine started”;
}
}
$car = new Car(new Engine());
$car->move();
In this example, the Car class is composed of an Engine object, demonstrating object composition. The Vehicle abstract class provides abstraction, hiding the internal details of the move method from outside.
I hope that you have clearly understood it.