Sling Academy
Home/PHP/PHP Object-Oriented Programming: A Complete Cheat Sheet

PHP Object-Oriented Programming: A Complete Cheat Sheet

Last updated: January 10, 2024

Overview

Grasping Object-Oriented Programming (OOP) in PHP paves the way for writing modular, reusable, and maintainable code. This cheat sheet covers everything from basic to advanced concepts, serving as a swift guide for PHP OOP.

Classes and Objects

In PHP, a class is a blueprint for creating objects while an object is an instance of a class. Here’s how you declare a class and create an object:

<?php

class Car {
    // Properties
    public $color;

    // Methods
    function setColor($color) {
        $this->color = $color;
    }
}

// Create an object
$myCar = new Car();
$myCar->setColor('blue');

?>

Output:

$myCar->color; // Outputs: blue

Properties and Methods

Properties represent characteristics of an object, and methods are actions an object can perform. Visibility keywords such as public, protected, or private define access level.

<?php

class Car {
    private $model;
    public function setModel($model) {
        $this->model = $model;
    }
    public function getModel() {
        return $this->model;
    }
}

$myCar = new Car();
$myCar->setModel('Tesla Model S');

echo $myCar->getModel();
?>

Output:

Tesla Model S

Inheritance

Inheritance allows a class to take on properties and methods from another class. Below, ElectricCar extends Car:

<?php

class Car {
    protected $model;

    public function setModel($model) {
        $this->model = $model;
    }

    public function getModel() {
        return $this->model;
    }
}

class ElectricCar extends Car {
    private $batteryLife;

    public function setBatteryLife($life) {
        $this->batteryLife = $life;
    }

    public function getBatteryLife() {
        return $this->batteryLife;
    }
}

$myTesla = new ElectricCar();
$myTesla->setModel('Tesla Model 3');
$myTesla->setBatteryLife('310 miles');

?>

Output:

$myTesla->getModel(); // Outputs: Tesla Model 3
$myTesla->getBatteryLife(); // Outputs: 310 miles

Encapsulation

Encapsulation is achieved by restricting direct access to some of an object’s components and can be enforced using visibility keywords. Let’s reinforce encapsulation in our Car class:

<?php

class Car {

    private $model;

    public function setModel($model) {
        $this->model = $model;
    }

    public function getModel() {
        return $this->model;
    }
}

?>

Polymorphism

Polymorphism allows methods to have different implementations based on the subclass they belong to. Here we override the getModel() method in ElectricCar:

<?php

class Car {
    protected $model;

    public function setModel($model) {
        $this->model = $model;
    }

    public function getModel() {
        return $this->model;
    }
}

class ElectricCar extends Car {
    public function getModel() {
        return 'Electric Car: ' . $this->model;
    }
}

$myCar = new Car();
$myCar->setModel('Audi A4');
$myTesla = new ElectricCar();
$myTesla->setModel('Tesla Model X');

echo $myCar->getModel();
echo "\n";
echo $myTesla->getModel();
?>

Output:

Audi A4
Electric Car: Tesla Model X

Interfaces

Interfaces specify what methods a class must implement, without defining how these methods should be handeled. A class can implement multiple interfaces:

<?php

interface Chargeable {
    public function charge();
}

interface GPSInterface {
    public function getCoordinates();
}

class ElectricCar extends Car implements Chargeable, GPSInterface {
    public function charge() {
        // Implementation for charge
    }

    public function getCoordinates() {
        // Implementation for getCoordinates
    }
}

?>

Abstract Classes

Abstract classes cannot be instantiated and are used as a base for other classes. Methods defined as abstract in an abstract class must be implemented by subclasses:

<?php

abstract class Vehicle {
    protected $model;

    abstract public function startEngine();

    public function setModel($model) {
        $this->model = $model;
    }

    public function getModel() {
        return $this->model;
    }
}

class Car extends Vehicle {
    public function startEngine() {
        echo "Engine of " . $this->getModel() . " started";
    }
}

$myCar = new Car();
$myCar->setModel('Fiat Punto');
$myCar->startEngine();

?>

Output:

Engine of Fiat Punto started

Traits

Traits are a mechanism for reusing code in single inheritance languages like PHP. They can have methods and abstract methods:

<?php

trait GPSLogger {
    public function logCoordinates() {
        echo "Logging current coordinates.";
    }
}

class Car {
    use GPSLogger;
    // Car class code here
}

$myCar = new Car();
$myCar->logCoordinates();

?>

Output:

Logging current coordinates.

Naming Conventions and Autoloading

Adhere to the PSR standards for naming conventions. With autoloading, you can include classes without the need for explicit require or include statements:

composer dump-autoload

Use composer and PSR-4 for autoloading your classes, here’s an example of the composer.json file:

{
    "autoload": {
        "psr-4": {"MyApp\\": "src/"}
    }
}

Then, you can simply use those classes without requiring every file:

<?php

use MyApp\Car;

// Your PHP code that uses Car

?>

Note: Remember to run composer dump-autoload after adding new classes or directories.

Conclusion

This cheat sheet encapsulates the key components of PHP OOP. By understanding and utilizing these principles effectively, you can greatly enhance the quality and sophistication of your PHP applications.

Next Article: Using traits in PHP classes: A practical guide

Previous Article: PHP class destructors: A practical guide

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array