OOP in PHP: What You Need to Know

PHP added object-oriented programming (OOP) to give structure and organization to code. You can group reusable code to avoid repeats.
Let’s get started.
What Is OOP in PHP?
The OOP in PHP means object-oriented programming. It is a way to organize code using classes and objects.
A class defines the structure and behavior of objects. It defines what something can do and what data it holds. An object is a real thing built from that class.
You can create many objects from one class, each with its own data.OOP in PHP helps you group related code together.
You can reuse parts and make changes. So you don’t have to rewrite your whole code when you make changes. It also helps you split work across files and teams.
So, why do you have to use OOP?
Here is why you should use it:
A class holds both data and the code that works on it.
You can create base classes and extend them. That saves time and avoids repeats.
You can control what parts of a class others can use to keep the rest of your code safe from unwanted changes.
The change only affects objects made from it if you update a class. That lowers the risk of bugs.
OOP helps split tasks. Each person can work on their own class without touching the rest.
Procedural vs Object-Oriented Programming
Procedural code runs step by step, like a list of instructions. You write functions, then call them in order.
It works well for small tasks. But as projects grow, it will be hard to manage. OOP groups code by purpose. You build classes with related data and actions.
Then you create objects from those classes. Each object handles its work.
Here are key differences:
Procedural:
Uses functions
Focuses on tasks
Shares data across the program
Harder to scale
OOP:
Uses classes and objects
Focuses on data and behavior
Keeps data inside each object
Easier to grow and manage
Classes and Objects
The PHP class is a plan. It defines what an object can do and what it knows. An object is a real thing made from that plan.
You use the class
keyword to create a class in PHP. Then you use the new
keyword to create objects from it.
Here is a quick example:
class Book {
public $title;
public function read() {
echo "You open the book and start reading.";
}
}
$myBook = new Book();
$myBook->title = "The Silent Island";
echo $myBook->title;
$myBook->read();
Output:
The Silent Island
You open the book and start reading.
This Book
class has one property, $title
, and one method, read()
. You create an object from it and give it a title.
Then you call the method to do something with the object. A property holds data inside a class.
A method is a function inside a class that does something. You use properties to store information and use methods to act on that information.
Access Modifiers
Access modifiers control who can use or change parts of a class. You use them to protect your data and decide what other code can reach.
PHP gives you three options:
public
allows anyone to use itprotected
allows only the class and its child classes can use itprivate
works for only the class itself can use it
Here is a clear example:
class BankAccount {
public $owner;
private $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
public function getBalance() {
return $this->balance;
}
}
$owner
is public. You can change it from anywhere.$balance
is private. Only the class can change or read it.deposit()
andgetBalance()
are public methods that safely update or show the balance.
Use private
when you want full control. Use protected
if a subclass might need access. Use public
when you want others to use or update it.
Constructors and Destructors
A constructor sets up the object when you create it. A destructor runs when the object is no longer needed.
The constructor is a method called __construct()
in PHP. You can pass values to it and use them to set properties.
For instance:
class Dog {
public $name;
public function __construct($dogName) {
$this->name = $dogName;
echo "$this->name is ready.<br>";
}
public function bark() {
echo "$this->name barks.";
}
public function __destruct() {
echo "<br>$this->name goes to sleep.";
}
}
You can use the class as follows:
$myDog = new Dog("Rex");
$myDog->bark();
So, here:
__construct()
runs first. It sets the name and prints a message.bark()
works like a normal method.__destruct()
runs when the script ends or the object is no longer used.
The parent
and self
Keywords
The parent
and self
keywords help you work with classes in an organized way, especially when you use inheritance.
parent
is used to refer to the parent class. You can use it to call a method or access a property from the parent class.self
refers to the current class itself. It is used to call static methods or properties.
This is an example that shows you how these work together:
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function speak() {
echo "$this->name makes a sound.";
}
}
class Dog extends Animal {
public function __construct($name) {
parent::__construct($name);
}
public function speak() {
echo "$this->name barks.";
}
}
$dog = new Dog("Rex");
$dog->speak();
Here is how it works:
parent::__construct($name)
calls the parent class's constructor to set the$name
property.self
is used in the same class to refer to static properties or methods, but we do not need it here because we are working with instance methods.
To use self
with static methods:
class Car {
public static $wheels = 4;
public static function showWheels() {
echo "A car has " . self::$wheels . " wheels.";
}
}
Car::showWheels();
The self::$wheels
accesses the static property within the same class.
Abstract Classes and Methods
An abstract class is a class that cannot be used to create objects directly. It is meant to be inherited by other classes.
You use it when you want to define methods that must be implemented by the child classes, but the parent class itself should not be used to create objects.
An abstract method is a method without a body. It just has a declaration and needs to be implemented by any class that inherits the abstract class.
For an example:
abstract class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function makeSound(); // Abstract method
}
class Dog extends Animal {
public function makeSound() {
echo "$this->name barks.";
}
}
$dog = new Dog("Rex");
$dog->makeSound();
Here, the Animal
class is abstract, so you cannot create an object of it directly. While the makeSound()
method is abstract. This forces the Dog
class to provide its own version of makeSound()
.
Traits
A trait in PHP is a way to share methods across multiple classes without using inheritance.
Traits allow you to reuse code in different classes. It avoids the limitations of single inheritance.
We can say it is a collection of methods that can be "added" to different classes. This helps when you need to reuse functionality across different classes without making them share a common parent.
Here is an example:
trait Logger {
public function log($message) {
echo "Log: $message";
}
}
class User {
use Logger;
public $name;
public function __construct($name) {
$this->name = $name;
}
}
class Product {
use Logger;
public $productName;
public function __construct($productName) {
$this->productName = $productName;
}
}
$user = new User("John");
$user->log("User logged in.");
$product = new Product("Laptop");
$product->log("Product added to cart.");
The Logger
trait defines a method log()
. Both User
and Product
classes use this trait, so they both can call log()
with no repeat of the code.
Wrapping Up
In this guide, you learned the basics of object-oriented programming (OOP) in PHP. Here's a quick recap of what you've covered:
Classes and Objects: You learned how to define a class and create objects from it.
Properties and Methods: You explored how to store data in properties and define actions with methods.
Access Modifiers: You learned about
public
,private
, andprotected
to control access to class properties and methods.Constructors and Destructors: You saw how constructors set up objects when created and destructors clean up when objects are no longer needed.
Inheritance: You learned how to use parent and child classes, and how the
parent
andself
keywords help manage relationships between classes.Abstract Classes and Methods: You discovered how abstract classes enforce rules on child classes and make sure they implement necessary methods.
Traits: You learned how traits allow code reuse across different classes without the need for inheritance.
Visit our coding blog or check the PHP manual to read more PHP tutorials.
Subscribe to my newsletter
Read articles from Montasser Mossallem directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
