Object-oriented programming(OOP) is a popular programming model used in present time software development. With OOP, programmers can organize code into reusable, modular components, which makes software development more efficient and easier to maintain. PHP, one of the most popular server side scripting languages,supports OOP concepts and provides developers with powerful tools to create robust and scalable applications.
In this article we will take closer look at oops in PHP and explore benefits it offers to developers.We will also discuss essential OOP concepts and how to use them in PHP programming.
What is Object-Oriented Programming.(OOP)?
Object-Oriented Programming is a programming model that focuses on creating software components that can be reused and combined to create complex/big applications.OOP is built around the concept of objects which represent real world entities or concepts. An object is a self contained unit that has properties and methods that define its behaviour.
PHP and OOP:
PHP supports OOP concepts and starting from PHP5 it provides robust support for OOP programming. OOP in PHP enables developers to create complex applications by breaking them down into smaller, reusable components. OOP in PHP allows developers to write more organized and maintainable code which is easier to debug and extend.
Object-Oriented Programming(OOP) in PHP has a large number of methods and keywords that are used to create classes,objects & methods.Here are some of most commonly used Object-Oriented Programming methods and keywords in PHP programming:
- Methods:
- __construct():a special method that is automatically called when an object is instantiate.
- __destruct():a special method that is automatically called when an object is destroy.
- __get(): a method that is called when an inaccessible property is accessed.
- __set(): a method that is called when an inaccessible property is set.
- __call(): a method that is called when a not accessible method is called.
- static: a keyword used to define static methods and properties.
- final: a keyword used to stop a class from being sub classed or a method from being overridden.
- abstract: a keyword used to define abstract classes & methods.
- interface: a keyword used to define interfaces.
- Keywords:
- class:a keyword used to define a class.
- new:a keyword used to create an object instance of a class.
- extends : a keyword used to define inheritance between classes.
- public :a keyword used to declare a property/method as publicly accessible.
- private -a keyword used to declare a property or method as accessible only within the class that defines it
- protected -a keyword used to declare a property or method as accessible only within the class that defines it and its subclasses
- this -a keyword used to refer to the current object instance within a class method
- self - a keyword used to refer to the current class within a class method
- parent - a keyword used to refer to the parent class within a class method
These are just a few of the many methods & keywords available in OOP in PHP. By understanding and using these methods and keywords effectively, you can create more powerful and efficient object-oriented code.
Essential OOP Concepts:
- Classes and Objects:
- Regular Classes Regular classes are the most common type of class in PHP and they can be instantiated to create objects.These classes can have properties and methods, which can be accessed using object notation.
- Regular classes must have a class keyword followed by a name and a set of curly braces.
- Class names should follow CamelCase naming convention.
- A class must be instantiated before it can be used to create objects.
- Properties and methods must have an access modifier, which determines their visibility.The three access modifiers are public, protected and private.
- A class can inherit from another class using the extends keyword.
- Abstract Classes Abstract classes are similar to regular classes but they cannot be instantiated on their own. Instead, they are meant to be extended by other classes. Abstract classes can have abstract methods, which are methods without implementation.These methods must be implemented by any class that extends the abstract class.
- Abstract classes must have an abstract keyword before the class keyword.
- An abstract class cannot be instantiated on its own.
- Abstract classes can have abstract methods which are declared without an implementation.
- Any class that extends an abstract class must implement all of its abstract methods.
- Interfaces Interfaces are alike to abstract classes but they can only have method signatures and constants.Any class that implements an interface must implement all of its methods. Interfaces are used to define a set of methods that must be implemented by any class that wants to use them.
- Interfaces must have an interface keyword followed by a name and a set of curly braces.
- Interfaces can only have method signatures and constants not properties or method implementations.
- Any class that implements an interface must implement all of its methods.
- Encapsulation:
- Public:
- Private :
- Protected :
- Inheritance:
- Polymorphism:
- Abstraction:
Classes define the blueprint or structure of an object, while objects are instances of a class. A class is a template that defines the properties and methods of an object, while an object is a concrete realization of a class.
In PHP there are three types of classes and objects: regular classes, abstract classes and interfaces.Let's take a look at each of them and their rules.
Rules:
Example:
<?php
class Car {
public $make;
public $model;
public function start() {
//code to start the car
}
private function checkFuel() {
//code to check the level of fuel
}
}
?>
Rules:
Example:
<?php
abstract class Vehicle {
public $make;
public $model;
abstract public function start();
}
?>
Rules:
Example:
<?php
interface Printable {
public function print();
}
?>
In summary regular classes, abstract classes and interfaces all have different rules and use cases in PHP. Regular classes are the most common and can be instantiated to create objects while abstract classes and interfaces are used for more specialized cases, such as creating blueprints for other classes or defining a set of methods that must be implemented by other classes.
Full Example of classes and objects in PHP.Imagine we are building a simple website for a library, and we want to create a class for the books that will be displayed on the site.We can create a Book class that will have properties for the title, author, and number of pages.
<?php
class Book {
public $title;
public $author;
public $pages;
}
?>
We can then create object of the BOOK class and set its properties...
<?php
$book1 = new Book();
$book1->title = "To Kill a Mockingbirds";
$book1->author = "Harry Lee";
$book1->pages = 281;
?>
We can also create additional objects of the BOOK class and set their properties...
<?php
$book2 = new Book();
$book2->title = "The Great Gat sby";
$book2->author = "F. Scott Fitz gerald";
$book2->pages = 180;
$book3 = new Book();
$book3->title = "Pride and Pre judice";
$book3->author = "Jane Aus";
$book3->pages = 279;
?>
We can then display the properties of each object using the echo statement.
<?php
echo $book1->title; // Output: To Kill a Mockingbird
echo $book2->author; // Output: F. Scott Fitzgerald
echo $book3->pages; // Output: 279
?>
We can also define methods with in the Book class to perform various tasks such as calculating the number of pages read per hour.
<?php
class Book {
public $title;
public $author;
public $pages;
public function readPagesPerHour($hours) {
return $this->pages / $hours;
}
}
?>
We can then call method on an object of the BOOK class...
<?php
$book1 = new Book();
$book1->title = "To Kill a Mockingbird";
$book1->author = "Harper Lee";
$book1->pages = 281;
echo $book1->readPagesPerHour(2); // Output: 140.5
?>
As you can see classes and objects in PHP provide a powerful way to encapsulate data and logic in reusable components. By defining a class, we can create multiple instances of that class (i.e.objects) with their own unique properties and methods.This makes our code more modular and easier to maintain as well as more efficient and scalable.
Encapsulation is a mechanism that hides the internal details of an object and exposes only the necessary information. It ensures that the data inside an object is not accessible from outside the object. It is an important concept in Object-Oriented Programming(OOP) that allows you to hide the implementation details of a class from the outside world.This helps to prevent accidental modification of class properties and methods and ensures that they are only accessed and modified in a controlled way. In PHP,encapsulation can be achieved using access modifiers such as public, private and protected.
Public properties and methods are accessible from anywhere in the code both inside and outside of the class. This means that they can be accessed by objects, functions, and other classes.
Private properties and methods are only accessible from with in the class. They cannot be accessed by objects functions or other classes outside of the class. This means that the value of a private property can only be set or retrieved by methods within the same class.
Protected properties and methods are only accessible from within the class and its subclasses. This means that they cannot be accessed by objects or functions outside of the class but they can be accessed by subclasses that inherit from the class.
Here example of Encapsulation in PHP:
<?php
class BankAccount {
private $balance;
public function deposit($amount) {
$this->balance += $amount;
}
public function withdraw($amount) {
if ($amount <= $this->balance) {
$this->balance -= $amount;
} else {
echo "Insufficient funds";
}
}
public function getBalance() {
return $this->balance;
}
}
?>
In this example, we define a Bank Account class with a private property $balance and three methods: deposit(), withdraw()and getBalance(). The deposit() method allows a user to add money to their account, while the withdraw() method allows them to remove money from their account. The
getBalance()
method allows them to check their current account balance.
Note that the $balance property is marked as private, which means that it can only be accessed within the class itself. This ensures that the balance can only be modified by the deposit() and withdraw() methods, and cannot be accessed or modified directly from outside the class. This helps to prevent accidental modification of the balance and ensures that it is only accessed and modified in a controlled way.
Here an example of how to use the Bank Account class:
<?php
$account = new BankAccount();
$account->deposit(1000);
$account->withdraw(500);
echo "Acc Balance: " . $account->getBalance();
?>
In this example we create a new Bank Account object, deposit 1000 into the account, withdraw 500 from the account, and then print the current balance using the getBalance() method. Note that we can only access the balance using the getBalance() method, and cannot modify it directly.
By encapsulating the balance property and only allowing it to be accessed and modified through controlled methods, we can ensure that the account balance is always accurate and that it cannot be accidentally modified or tampered with.
Inheritance is a mechanism that enables one class to inherit properties and methods from another class. Inheritance promotes code reuse, and it simplifies the design and maintenance of complex applications.It is a powerful feature in Object-Oriented Programming (OOP) that allows you to create new classes that are based on existing classes, inheriting their properties and methods. In PHP, you can use the extends keyword to create a subclass that inherits from a parent class.
Here example of inheritance in PHP:
<?php
class Animal {
protected $name;
protected $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function eat() {
echo "{$this->name} eating..."; }
}
class Dog extends Animal {
public function bark() {
echo "{$this->name} barking..."; }
}
?>
In this example we define an Animal class with two protected properties ($name and $color) and a eat() method. We then define a Dog class that extends the Animal class, and adds a bark() method.
Note that the Dog class uses the extends keyword to inherit from the Animal class.This means that the Dog class will have access to all of the properties and methods of the Animal class, as well as its own bark() method.
Here example of how to use the Dog class:
<?php
$dog = new Dog('Fido', 'Brown');
$dog->eat(); // Output: Fido eating...
$dog->bark(); // Output: Fido barking...
?>
In this example we create a new DOG object and pass in a name and color to its constructor.We then call its eat() and bark() methods which were inherited from the Animal class and defined in the Dog class respectively.
By using inheritance we can create new classes that are based on existing classes inheriting their properties and methods and adding new functionality. This allows us to write more efficient and reusable code and makes it easier to organize and maintain our programs
Polymorphism is the ability of an object to take on different forms or behaviors. In PHP, polymorphism is achieved through method overriding and method overloading.It is an important concept in Object-Oriented Programming (OOP) that allows objects of different classes to be treated as if they were the same type. This is achieved by using inheritance and method overriding, which allows a subclass to provide its own implementation of a method that is already defined in its parent class. In PHP, polymorphism can be achieved using the extends keyword and the override keyword.
Here example of polymorphism in PHP:
<?php
class Shape
{
public function getArea()
{
return 0;
}
}
class Circle extends Shape
{
private $radius;
public function __construct($radius)
{
$this->radius = $radius;
}
public function getArea()
{
return 3.14 * $this->radius * $this->radius;
}
}
class Square extends Shape {
private $length;
public function __construct($length){
$this->length = $length;
}
public function getArea()
{
return $this->length * $this->length; }
}
?>
In this example we define a Shape class with a getArea() method that returns 0.We then define two subclasses: Circle and Square, both of which extend the Shape class and provide their own implementation of the getArea() method.
Note that the getArea() method is defined in the Shape class and overridden in the Circle and Square classes. This allows objects of the Circle and Square classes to be treated as if they were objects of the Shape class because they share the same method signature.
Here example of how to use the Shape, Circle, and Square classes:
<?php
$shapes = array(
new Circle(5),
new Square(4),
new Circle(3)
);
foreach ($shapes as $shape){
echo "Area: " . $shape->getArea() . "<br>";
}
?>
In this example we create an array of Shape objects that contains two Circle objects and one Square object. We then iterate over the array and call the getArea() method on each object which will call the appropriate implementation of the method in each subclass.
By using polymorphism we can write more flexible and extensible code that can be easily adapted to different situations. This allows us to write code that is more maintainable, reusable and efficient and makes it easier to add new functionality to our programs.
Abstraction is a mechanism that allows developers to create generalized models of realworld entities / concepts. It helps to reduce complexity and increase the reusability of code.It is an important concept in Object-Oriented Programming (OOP) that allows us to hide the implementation details of a class from its users, while still providing a clear and concise interface for interacting with that class. In PHP we can achieve abstraction by using abstract classes and abstract methods.
Here example of abstraction in PHP:
<?php
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
public function getColor() {
return $this->color;
}
abstract public function getArea();
}
class Circle extends Shape {
private $radius;
public function __construct($color, $radius)
{
parent::__construct($color);
$this->radius = $radius;
}
public function getArea() {
return 3.14 * $this->radius * $this->radius;
}
}
class Square extends Shape {
private $length;
public function __construct($color, $length) {
parent::__construct($color);
$this->length = $length;
}
public function getArea() {
return $this->length * $this->length;
}
}
?>
In this example we define a Shape class with a getArea() method that returns 0. We then define two subclasses: Circle and Square, both of which extend the Shape class and provide their own implementation of the getArea() method.
Note that the getArea() method is defined in the Shape class and overridden in the Circle and Square classes. This allows objects of the Circle and Square classes to be treated as if they were objects of the Shape class because they share the same method signature.
Here example of how to use the Shape, Circle and Square classes:
<?php
$shapes = array(
new Circle(5),
new Square(4),
new Circle(3)
);
foreach ($shapes as $shape) {
echo "Area : " . $shape->getArea() . "
";
}
?>
In this example We create an array of Shape objects that contains two Circle objects and one Square object.We then iterate over the array and call the getArea() method on each object which will call the appropriate implementation of the method in each subclass.
By using polymorphism we can write more flexible and extensible code that can be easily adapted to different situations.This allows us to write code that is more maintainable, reusable and efficient and makes it easier to add new functionality to our programs.
Benefits of OOP in PHP:
Reusability :OOP in PHP enables developers to write reusable code, which reduces development time and increases efficiency.
Modularity: OOP in PHP allows developers to break down complex applications into smaller manageable components.This improves the organization of code and makes it easier to maintain and debug.
Extensibility: OOP in PHP promotes the use of inheritance and polymorphism which allows developers to extend the functionality of existing code without modifying the original code.
Security: O O P in PHP enables developers to implement secure coding practices such as encapsulation and data hiding which helps to protect sensitive data from unauthorized access.
OOP in PHP is a powerful programming paradigm that enables developers to create scalable, efficient and maintainable applications. The essential OOP concepts in PHP including classes and objects, encapsulation, inheritance, polymorphism and abstraction, make it possible to create reusable, modular and secure code. By understanding the benefits of OOP in PHP developers can write better quality code that is easier to maintain and extend.