Object Composition and Abstractions in OOP

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:

<?php // 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();
Enter fullscreen mode Exit fullscreen mode

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.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Overlaxed's sub brand, cloudy storage, specializes in cloud storage.