PHP OOP - Classes and Objects

In PHP, Object-Oriented Programming (OOP) is a paradigm based on the concept of "objects", which are instances of "classes". Here's a concise guide to PHP OOP with Classes and Objects:


Class Definition

A class is like a blueprint for objects.

class Car { public $color; public $model; // Constructor public function __construct($color, $model) { $this->color = $color; $this->model = $model; } // Method public function getMessage() { return "The car is a $this->color $this->model."; } }

Creating Objects

An object is an instance of a class.

$car1 = new Car("red", "Toyota"); echo $car1->getMessage(); // Output: The car is a red Toyota. $car2 = new Car("blue", "Honda"); echo $car2->getMessage(); // Output: The car is a blue Honda.

OOP Concepts in PHP

  1. Properties: Variables inside a class (use $this->property inside class).

  2. Methods: Functions inside a class.

  3. Visibility:

    • public: Accessible from anywhere.

    • protected: Accessible in the class and subclasses.

    • private: Accessible only within the class.

  4. Constructor (__construct): Special method called when an object is created.

  5. Inheritance: A class can inherit from another class.

class ElectricCar extends Car { public $battery; public function __construct($color, $model, $battery) { parent::__construct($color, $model); $this->battery = $battery; } public function getBatteryStatus() { return "Battery capacity: $this->battery kWh."; } }

Other Advanced OOP Features

  • Interfaces

  • Traits

  • Abstract Classes

  • Namespaces

  • Static Properties and Methods

  • Magic Methods (__get, __set, __toString, etc.)