PHP Classes and Objects
Object-Oriented Programming (OOP) is a way of structuring code around real-world concepts called objects. Instead of writing a collection of separate functions and variables, OOP groups related data (properties) and behavior (methods) together inside a structure called a class. PHP fully supports OOP and it is the foundation of virtually every modern PHP framework including Laravel, Symfony, and WordPress's object-oriented core.
What Is a Class
A class is a blueprint or template. It defines what properties (data) and methods (behaviors) objects created from it will have. Think of a class as the design plan for a car: it specifies that every car has a brand, a color, and a speed, and that every car can accelerate and brake.
What Is an Object
An object is an instance of a class — an actual "car" built from that blueprint. Many objects can be created from a single class, and each object has its own independent set of property values.
Defining a Class
<?php
class Car {
// Properties (data the object holds)
public $brand;
public $color;
public $speed = 0;
// Method (behavior the object can perform)
public function accelerate($amount) {
$this->speed += $amount;
}
public function brake($amount) {
$this->speed -= $amount;
if ($this->speed < 0) {
$this->speed = 0;
}
}
public function getInfo() {
return $this->brand . " (" . $this->color . ") - Speed: " . $this->speed . " km/h";
}
}
?>
The $this keyword refers to the current object. Inside any method, $this->propertyName accesses the object's own property.
Creating Objects
Objects are created using the new keyword followed by the class name.
<?php
$car1 = new Car();
$car1->brand = "Toyota";
$car1->color = "Red";
$car1->accelerate(60);
$car2 = new Car();
$car2->brand = "BMW";
$car2->color = "Blue";
$car2->accelerate(100);
echo $car1->getInfo(); // Toyota (Red) - Speed: 60 km/h
echo $car2->getInfo(); // BMW (Blue) - Speed: 100 km/h
?>
Both objects are independent. Changing a property on $car1 does not affect $car2.
The Constructor Method
A constructor is a special method named __construct() that runs automatically when an object is created. It is used to initialize properties with values provided at the time of instantiation.
<?php
class Product {
public $name;
public $price;
public $inStock;
public function __construct($name, $price, $inStock = true) {
$this->name = $name;
$this->price = $price;
$this->inStock = $inStock;
}
public function getSummary() {
$status = $this->inStock ? "Available" : "Out of stock";
return $this->name . " - $" . $this->price . " (" . $status . ")";
}
}
$laptop = new Product("Laptop Pro", 999.99);
$phone = new Product("Smartphone X", 499.99, false);
echo $laptop->getSummary(); // Laptop Pro - $999.99 (Available)
echo $phone->getSummary(); // Smartphone X - $499.99 (Out of stock)
?>
The Destructor Method
The __destruct() method runs automatically when an object is no longer referenced or when the script ends. It is used for cleanup tasks like closing database connections or saving final state.
<?php
class FileWriter {
private $handle;
public function __construct($filename) {
$this->handle = fopen($filename, "w");
echo "File opened.\n";
}
public function write($text) {
fwrite($this->handle, $text);
}
public function __destruct() {
fclose($this->handle);
echo "File closed.\n";
}
}
$writer = new FileWriter("output.txt");
$writer->write("Hello from OOP!");
// __destruct() runs automatically when $writer goes out of scope
?>
Static Properties and Methods
Static properties and methods belong to the class itself — not to any specific object. They are accessed using the class name and the :: operator.
<?php
class Counter {
public static $count = 0;
public function __construct() {
self::$count++; // self:: refers to the class itself
}
public static function getCount() {
return self::$count;
}
}
$a = new Counter();
$b = new Counter();
$c = new Counter();
echo Counter::getCount(); // Outputs: 3
echo Counter::$count; // Outputs: 3
?>
Class Constants
<?php
class Circle {
const PI = 3.14159265;
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return self::PI * $this->radius ** 2;
}
}
$circle = new Circle(5);
echo "Area: " . round($circle->area(), 2); // Area: 78.54
echo Circle::PI; // Access constant directly from class
?>
Constructor Property Promotion (PHP 8)
PHP 8 introduced a shorter syntax for declaring and initializing properties directly in the constructor signature.
<?php
class User {
// Properties are declared and assigned in one step
public function __construct(
public string $name,
public string $email,
public int $age = 0
) {}
}
$user = new User("Alice", "alice@example.com", 30);
echo $user->name; // Alice
echo $user->email; // alice@example.com
?>
Key Points
- A class is a blueprint; an object is an instance of that class created with
new ClassName(). - Properties store data; methods define behavior. Both belong to a class.
$thisrefers to the current object instance inside a method.- The
__construct()method runs automatically when an object is created — use it to initialize properties. - The
__destruct()method runs when an object is destroyed — use it for cleanup. - Static properties and methods (accessed with
ClassName::orself::) belong to the class, not individual objects. - PHP 8 constructor property promotion lets properties be declared and assigned directly in the constructor signature.
