A complex web application needs proper organization and maintenance to keep your code structured. This is where PHP Object-Oriented Programming (OOP) comes in. OOP lets you divide your code into reusable and easy-to-manage pieces.
Table of Content
We will cover the following topics in this tutorial:
- What is object-oriented programming?
- PHP OOP principles.
- Basic OOP concepts in PHP.
- Examples.
Let’s move on to what object-oriented programming is and how it works.
Understand Object-Oriented Programming (OOP) in PHP
Object-Oriented Programming (OOP) organizes code into objects. An object groups related data and functions. This makes code easier to manage and reuse.
OOP helps structure PHP applications better. Here is why it is useful:
- Classes let you reuse code instead that you write classes again.
- Organized code makes updates simpler.
- Large projects become easier to manage.
- Teams work when you use shared classes.
- Encapsulation protects sensitive data.
OOP uses four main concepts:
- Encapsulation.
- Abstraction.
- Inheritance.
- Polymorphism.
Let’s take each one in-depth within the following section.
Principles of OOP in PHP
1- Encapsulation
Encapsulation controls how data inside an object is accessed and modified. A class can keep certain properties private.
It prevents direct changes from outside the class. Instead, it provides methods (getters and setters) to access or update the data. This prevents unintended modifications and keeps data secure.
class Member {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
$user = new Member();
$user->setName("FlatCoding Member Name");
echo $user->getName(); Output:
FlatCoding Member Name
The $name property stays private. Direct access is blocked. So, data stays controlled and secure.
2- Abstraction
Abstraction simplifies code and hides unnecessary details. A class can provide only the essential methods, and it keeps internal workings hidden. This reduces complexity.
For example:
abstract class Vehicle {
abstract public function startEngine();
public function stopEngine() {
echo "Engine stopped";
}
}
class Car extends Vehicle {
public function startEngine() {
echo "Car engine started";
}
}
$car = new Car();
$car->startEngine();
$car->stopEngine(); Here is the output:
Car engine started
Engine stopped
The Vehicle defines a common structure, but Car provides specific behavior. The user does not need to know how the engine starts internally, just how to call the method.
3-Inheritance
Inheritance lets one class (child class) take properties and methods from another class (parent class).
This avoids duplicate code and makes changes easier. The child class can also override methods from the parent class to change behavior.
For Example:
class Animal {
public function makeSound() {
echo "Some sound";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Bark";
}
}
$dog = new Dog();
$dog->makeSound(); The output:
Bark
The Dog class inherits from Animal. But overrides the makeSound method. This lets it customize behavior while still being part of the Animal class.
4-Polymorphism
Polymorphism allows multiple classes to use the same method name but implement different behaviors. This makes code more scalable.
For example:
interface Shape {
public function getArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function getArea() {
return pi() * $this->radius * $this->radius;
}
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
}
$circle = new Circle(5);
$rectangle = new Rectangle(4, 6);
echo $circle->getArea();
echo $rectangle->getArea(); The output:
78.539816339745
24
In the following section, we will cover in-depth OOP concepts in PHP.
Basic OOP Concepts in PHP
Below are the core concepts you need to understand.
Classes and Objects
A class is a template that allows you to make objects. An object is a copy of a class. A class sets the variables and functions that its objects will use.
For example:
class Motorcycle {
public $brand;
public function ride() {
echo "Riding a " . $this->brand;
}
}
$bike1 = new Motorcycle();
$bike1->brand = "Harley-Davidson";
$bike1->ride(); The output:
Riding a Harley-Davidson
The Motorcycle class defines a property ($brand) and a method (ride). The $bike1 object is created from this class.
Properties and Methods
Properties store data inside a class and methods to perform actions. Methods can access and modify properties.
For example:
class Person {
public $name;
public function sayHello() {
echo "Hello, my name is " . $this->name;
}
}
$person = new Person();
$person->name = "Montasser";
$person->sayHello(); The output:
Hello, my name is Montasser
The Person class has a property ($name) and a method (sayHello). The method uses $this->name to access the object’s data.
Access modifiers
Access modifiers control how properties and methods can be accessed.
- Public: Accessible from anywhere.
- Private: Accessible only within the class.
- Protected: Accessible within the class and subclasses.
Here is an example:
class BankAccount {
private $balance = 1000;
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount();
echo $account->getBalance(); The output:
1000
The $balance is private, so direct access is blocked. The getBalance method allows controlled access.
Constructors and Destructors
A constructor runs when an object is created. A destructor runs when an object is no longer needed.
Example:
class FlatCodingUser {
public function __construct() {
echo "User of flatcoding.com created";
}
public function __destruct() {
echo "User of flatcoding.com deleted";
}
}
$user = new FlatCodingUser(); Output:
User of flatcoding.com created
User of flatcoding.com deleted
The constructor initializes the object, and the destructor cleans up resources.
Static Properties and Methods
Static properties and static methods belong to the class, not to an instance. You call them when you use ClassName::methodName().
Example:
class MathHelper {
public static function add($a, $b) {
return $a + $b;
}
}
echo MathHelper::add(5, 3); Output:
8
The add the method is static, so you do not need to create an object to use it.
Namespaces in PHP OOP
Namespaces prevent name conflicts when you use multiple classes with the same name.
namespace App\Models;
class FlatCodingUser {
public function getInfo() {
echo "This info for user of FlatCoding.com";
}
}
$user = new \App\Models\FlatCodingUser();
$user->getInfo();The output:
This info for user of FlatCoding.com
The App\Models namespace keeps the FlatCodingUser class is separate from other classes with the same name.
Traits in PHP
Traits allow code reuse in multiple classes without inheritance.
For example:
trait Logger {
public function log($message) {
echo "Log: " . $message;
}
}
class Order {
use Logger;
}
$order = new Order();
$order->log("Order placed"); The output:
Log: Order placed
The Logger trait provides a log method that any class can use.
Exception Handling in PHP OOP Programming
It lets you manage errors and does not need the script to stop.
Here is an example:
class Machine {
public function operate($speed, $power) {
if ($power == 0) {
throw new Exception("Machine cannot run without power");
}
return "Machine running at " . $speed . " speed.";
}
}
try {
$machine = new Machine();
echo $machine->operate(100, 0);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} The output:
Error: Machine cannot run without power
The try block runs the code, and the catch block catches errors if they happen. Instead of stopping the script it shows the error message.
Wrapping Up
You learned the basics of Object-Oriented Programming (OOP) in PHP and how it helps structure code for better reusability and organization. You also explored key OOP principles and how they work in PHP.
Here is a quick recap:
- OOP concepts let you structure code with classes and objects. Also lets you control properties and methods.
- Encapsulation restricts direct access to data inside a class.
- Abstraction hides unnecessary details and shows only what is needed.
- Inheritance lets one class reuse another class’s properties and methods.
- Polymorphism allows different classes to use the same method in different ways.
- Access modifiers control where properties and methods can be used.
- Constructors and destructors handle setup and cleanup when you use objects.
- Static properties and methods belong to a class instead of an object.
- Namespaces prevent conflicts when classes have the same name.
- Traits let multiple classes share code without using inheritance.
- Exception handling catches errors and prevents the script from stopping.
FAQ’s
What is Object-Oriented Programming (OOP) in PHP?
Why use OOP in PHP?
What are the main principles of OOP in PHP?
- Encapsulation restricts direct access to data.
- Abstraction hides complex details and shows only necessary parts.
- Inheritance allows a class to use another class’s properties and methods.
- Polymorphism lets different classes use the same method in different ways.
What is encapsulation in PHP OOP?
How does abstraction work in PHP?
What is inheritance in PHP OOP?
What is polymorphism in PHP?
How does exception handling work in PHP OOP?
Similar Reads
In some cases, you need to handle a lot of data or simply try to open a file, or read…
The filter_var_array() appeared to make input validation simple and sanitization in PHP. It handles multiple inputs with different filters was…
Updating documents in MongoDB with PHP involves using the updateOne or updateMany methods from the MongoDB PHP library. These methods allow for precise updates,…
Essentially, “require” and “require_once” are directives in PHP to include and evaluate a specific file during the execution of a…
The array_pop function in PHP gives you a direct way to take the last element from an array. Understand the…
You can use the array_fill function in PHP when you must fill an array with one value. You may want…
When working with big arrays in PHP, things can get messy. That is where php array_chunk() steps in by providing…
The whole world of PHP programming revolves around data, be it numbers, text, or more complicated structures. Each of these…
Abstract class in PHP appeared to provide a way to define a structure for related classes and don't allow direct…
If you want to write good PHP code, strict mode should be on your radar. Strict mode—activated by the command declare(strict_types=1); at…