OOP (object-oriented programming) in PHP
OOP (object-oriented programming) in PHP is a programming paradigm in which programs consist of object-oriented classes and objects. In PHP, classes and objects are used to reuse code and to structure and organize complex applications.
To use OOP in PHP, a PHP developer must be familiar with key OOP concepts such as classes, objects, inheritance, and polymorphism.
Content
- A simple PHP class
- The four main principles of object-oriented programming in PHP
- Encapsulation with PHP
- Abstraction Encapsulation with PHP
- Inheritance with PHP
- Polymorphism with PHP
- Procedural programming vs Object-oriented programming in PHP
What does a simple PHP class look like?
<?php
// Defining a simple PHP class "Person
class Person
{
// Eigenschaften (Variablen)
public $name;
public $age;
// Constructor method
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
// Methoden (Functions)
public function getName()
{
return $this->name;
}
public function getAge()
{
return $this->age;
}
}
// Initialization of the "Person" class
$p1 = new Person("Max Mustermann", 35);
// Ausgabe der Eigenschaften des Objekts
echo "Name: " . $p1->getName() . "<br>";
echo "Alter: " . $p1->getAge() . "<br>";
?>
OOP in PHP is based on four main principles:
Encapsulation with PHP
This refers to the practice of bundling data and functions that operate on that data into a single unit, called an object. Encapsulation allows developers to hide the internal details and complexity of an object, and to provide a clear and consistent interface for interacting with it.
In this example, I show a simple PHP class for a bank account that uses the concepts of encapsulation.
The BankAccount class contains three methods: deposit()
, withdraw()
and getBalance()
. The $balance
variable is declared as a private
attribute of the class, which means that it can only be used within the class itself.
The deposit() method adds an amount to the current balance, while the withdraw()
method subtracts an amount from the current balance.
If an attempt is made to withdraw more money than is in the account, an exception is thrown. Finally, the getBalance()
method returns the current account balance.
Using encapsulation prevents the class from being manipulated from outside by accessing the $balance
variable directly.
Instead, the methods of the class must be used to change or query the account balance. This ensures that the account balance is always correct and consistent.
<?php
class BankAccount {
private $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
public function withdraw($amount) {
if ($amount > $this->balance) {
throw new Exception("Insufficient funds");
}
$this->balance -= $amount;
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount();
$account->deposit(100);
$account->withdraw(50);
echo $account->getBalance(); // Outputs 50
?>
Abstraction Encapsulation with PHP
This is the process of representing essential features of an object, without including irrelevant or unnecessary details. Abstraction allows developers to focus on the essential characteristics of an object, and to create classes that can be used to model real-world objects and relationships.
In this example I show a PHP class about abstraction. The Shape class is an abstract class that contains the getArea()
and getColor()
methods.
The getArea()
method is abstract, which means that it is not implemented in the abstract class and must be implemented by inheriting classes.
The Shape class is inherited from two classes: Square and Circle. Each of these classes implements its own version of the getArea()
method to calculate the area of
the respective geometric object.
By using abstraction, we can combine common properties and methods into the abstract Shape class without having to provide concrete implementations for each shape. This allows us to use the Shape class as the basis for different geometric shapes without having to define each shape separately.
<?php
abstract class Shape {
protected $color;
public function __construct($color = 'red') {
$this->color = $color;
}
abstract public function getArea();
public function getColor() {
return $this->color;
}
}
class Square extends Shape {
protected $length = 4;
public function getArea() {
return pow($this->length, 2);
}
}
class Circle extends Shape {
protected $radius = 5;
public function getArea() {
return M_PI * pow($this->radius, 2);
}
}
$circle = new Circle();
echo $circle->getArea(); // 78.53981633974483
$square = new Square();
echo $square->getColor(); // red
?>
Inheritance with PHP
This is the ability of a class to inherit the properties and methods of another class, called the parent class. Inheritance allows developers to create a hierarchy of classes, where each class can inherit the properties and methods of its parent class, and can also add its own unique features.
In this example I show a PHP class about inheritance. The Shape class is the base class and contains the $color property and the getColor()
method.
The Square, Circle and Triangle classes inherit from the Shape class and therefore can access the properties and methods of the base class.
Each inheriting class has its own specific properties and methods that it inherits from the base class. For example, the Square class has the $length property and the
getArea()
method, which calculates the area of the square. The Circle class has the $radius property and also the getArea()
method, which calculates the area of the circle.
The Triangle class has the $base and $height properties and the getArea()
method that calculates the area of the triangle.
By using inheritance, we can combine the common properties and methods in the base Shape class and inherit them from the inheriting classes. This allows us to repeat code and provides better organization and maintainability of the code.
<?php
class Shape {
protected $color;
public function __construct($color = 'red') {
$this->color = $color;
}
public function getColor() {
return $this->color;
}
}
class Square extends Shape {
protected $length = 4;
public function getArea() {
return pow($this->length, 2);
}
}
class Circle extends Shape {
protected $radius = 5;
public function getArea() {
return M_PI * pow($this->radius, 2);
}
}
class Triangle extends Shape {
protected $base = 4;
protected $height = 7;
public function getArea() {
return 0.5 * $this->base * $this->height;
}
}
$circle = new Circle();
echo $circle->getArea(); // 78.53981633974483
$triangle = new Triangle();
echo $triangle->getColor(); // red
$square = new Square();
echo $square->getArea(); // 16
?>
Polymorphism with PHP
This is the ability of different objects to respond to the same method call in different ways. Polymorphism allows developers to create objects with different implementations of the same method, and to use those objects interchangeably without needing to know the specific details of their implementation.
In this example I show a PHP class about polymorphism. The Shape class is an abstract class that contains the getArea()
and getColor()
methods. The getArea()
method is abstract,
which means that it is not implemented in the abstract class and must be implemented by inheriting classes.
The Shape class is inherited from three classes: Square, Circle and Triangle. Each of these classes has its own implementation of the getArea()
method to calculate the area of
the respective geometric object.
The printArea()
function takes an object of the Shape class as an argument and calls the getArea()
method to calculate and output the area of the geometric object. The function
is polymorphic because it can be used for any geometric object that inherits from the Shape class.
By using polymorphism, we can create a single function that can be used for different types of geometric objects. This allows us to reuse our code and make it more flexible.
<?php
abstract class Shape {
protected $color;
public function __construct($color = 'red') {
$this->color = $color;
}
abstract public function getArea();
public function getColor() {
return $this->color;
}
}
class Square extends Shape {
protected $length = 4;
public function getArea() {
return pow($this->length, 2);
}
}
class Circle extends Shape {
protected $radius = 5;
public function getArea() {
return M_PI * pow($this->radius, 2);
}
}
class Triangle extends Shape {
protected $base = 4;
protected $height = 7;
public function getArea() {
return 0.5 * $this->base * $this->height;
}
}
function printArea(Shape $shape) {
echo $shape->getArea();
}
$circle = new Circle();
printArea($circle); // 78.53981633974483
$triangle = new Triangle();
printArea($triangle); // 14
$square = new Square();
printArea($square); // 16
?>
These principles allow programs in PHP to be modular, scalable, and reusable, making it easier to develop and maintain applications.
Procedural programming vs Object-oriented programming in PHP
Procedural programming in PHP
Procedural programming is a programming paradigm that focuses on the use of functions and global variables to write a program. In contrast to object-oriented programming, where code is organized into classes, procedural programming involves writing code as a sequence of steps that are executed from top to bottom.
Procedural programming is still very common in PHP, although it does offer the option for object-oriented programming as well. Procedural programming can be simpler and faster to write in certain situations than object-oriented programming, especially for smaller projects. However, it can be more difficult to maintain and update the code over the long term.
Here is an example PHP script that is programmed procedurally
In this script we have defined two functions: calculateSum()
and calculateDifference()
.
These functions take two numbers as arguments and calculate the sum and difference of the two numbers, respectively.
We then defined the two variables $x and $y and called the functions to calculate the sum and difference of these two numbers.
This is a simple example of procedural programming in PHP, as we use a function to perform a specific task and use variables to store and manipulate data. However, this code is not very structured and would be ill-suited for larger or more complex applications. Object-oriented programming would be a better choice in these cases.
<?php
function calculateSum($x, $y)
{
return $x + $y;
}
function calculateDifference($x, $y)
{
return $x - $y;
}
$x = 5;
$y = 3;
$sum = calculateSum($x, $y);
$difference = calculateDifference($x, $y);
echo "The sum of $x and $y is $sum\n";
echo "The difference of $x and $y is $difference\n";
?>
Procedural programming or object-oriented programming?
Object-oriented programming (OOP) offers several benefits over procedural programming in PHP. These benefits include:
- Improved organization and readability: OOP allows you to organize your code into classes, which makes it easier to read and understand. This is especially useful for large and complex projects.
- Reusability: In OOP, you can create classes that can be used multiple times in different parts of your code. This allows you to avoid duplication and makes your code more efficient and maintainable.
- Encapsulation: OOP allows you to encapsulate your code, which means you can hide the implementation details of a class from the outside world. This allows you to create a clear and predictable interface for interacting with the class, which makes your code more reliable and maintainable.
- Polymorphism: OOP allows you to create classes that can be used interchangeably, even if they have different underlying implementations. This allows you to write code that is more flexible and adaptable.
- Overall, OOP offers a number of advantages over procedural programming in PHP, making it a better choice for many applications.
Still questions about OOP with PHP, then ask your questions in our Forum for PHP developers