DEV Community

Ghulam Mujtaba
Ghulam Mujtaba

Posted on

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay