In this article, we will be going through the concept of Object-Oriented Programming (OOP) in the PHP language. Before that, let me give you a brief introduction to the PHP language itself.
Created by Rasmus Lerdorf in 1993, PHP, which stands for hypertext preprocessor, is a very popular and widely used scripting language for building web and business applications. WordPress, which is a very popular content management system for websites, is powered by PHP, and Laravel, which is a framework that facilitates seamless web application development, is also run on PHP.
PHP is embedded in the HTML language, subsequently allowing it to be used in the creation of dynamic webpages. It is also integrated into various databases such as MySQL and Microsoft SQL Server, enabling robust database management. The PHP language can also be used for more than just accessing cookies; it can also be used to set cookies. The numerous uses and importance of the PHP language are enough reasons to discuss one of the most fundamental and popular programming models or paradigms widely used by software engineers: OOP.
Now let’s fully dive into the concepts of OOP in the PHP language.
Introduction to OOP
What is OOP? OOP is a model of programming that makes use of blocks of code called objects, which have unique data, attributes, and functions.
OOP is a perfect fit for programs that run on large and very complicated codes because it makes them easy to manage, update, and maintain. It also organises these codes into simple and reusable pieces.
Benefits of OOP
Reusability: one of the major benefits of OOP is its reusability. The reusability of OOP not only reduces time but also reduces redundancy and also allows programmers to follow the rule of thumb in programming, which is not repeating codes. A concept of OOP called inheritance also allows programmers to build on existing lines of code.
Structure: OOP allows programmers to structure their codes better, which makes lines of code easier to read than when they are written normally.
Security: a concept in OOP encapsulation that allows programmers to hide details of their codes for security reasons and only display necessary parts of the code without affecting the functionality of the code.
Cooperation: Using OOP eases collaboration amongst developers since each developer can focus on various aspects of the programmes without interfering with one another.
Time: OOP reduces the time taken to complete programmes, thereby increasing the productivity of developers.
Adaptability: polymorphism, which is a concept in OOP, allows the use of a function to produce different results depending on the class into which it is placed.
Classes and Objects
Classes and Objects are the fundamental concepts of OOP. They are the blueprints of OOP.
Classes
Classes serve as the blueprints for OOP. They contain attributes and functions known as methods in a class. The attributes serve as the properties of the class, and the methods are what the class can do.
Classes are created with the class keyword followed by the name of the class, and inside the class, the attributes and methods can be found. An example of a class is displayed below:
The class Car was defined using the class keyword. The $brand and $colour serve as the attributes of the Car class, and the get_brand and get_color functions are the methods of the Car class. The get_brand function is used to get the brand of the Car, while get_color is used to get the colour of an object of the Car class.
Objects
Objects are used to access the attributes and methods of a class. Objects are created using the ‘new’ keyword followed by the name of the object followed by a parenthesis. An object is created below to access the Car class attributes and methods.
The provided code's output is displayed below, demonstrating that the object $mercedes successfully accessed both the attributes of the Car class and its associated methods.
Constructor and Destructor
The Constructor and destructor are important concepts in OOP; they ensure proper initialization of code when the codes are run and ensure codes are destroyed immediately after they are run, respectively. Constructor and destructor are examples of magical methods in PHP. Before we fully delve into constructors and destructors, let's diverge and talk a little about magic methods.
What are magic methods? Magic methods are methods used in OOP that are already created with specified names and functions. When using magic methods, there is no need to define them since they have already been predefined, unlike normal methods that would need to be defined. Magic methods are always declared with a double underscore ‘__’ that serves as a prefix, just like the constructor and destructor methods, which are declared like this: ‘__construct’ and ‘__destruct’. We will be discussing the constructor and destructor methods now.
Constructor
A constructor is a magic method that is declared with the keyword __construct and initialises a class when it is used. When using a constructor, there is no need to call the attributes of the class separately, as this can be done with the constructor. I would be using the Car class to demonstrate the use of a constructor.
The constructor has already initialised the attributes of the Car class, so there was no need to manually set the attributes when creating a new object for the class.
Destructor
A destructor is a magic method that is declared with the __destruct keyword. It is declared when the class is no longer needed or needs to be deleted. The destructor magic method cleans up any resources, such as files and memory, the class might have used. I would be adding a destructor to the Car class we have been using.
The destructor method would automatically be called when the code is done running. The output of the code below shows the destructor being activated when the script has run its course.
Access modifiers
Access modifiers are keywords that determine how attributes and methods of a class can be accessed. They determine where the attributes and methods can be accessed and what can access them. There are three main access modifiers, and we will be discussing all three.
Public
The public access modifier is the least protected access modifier among all three main access modifiers. Attributes and methods with the public access modifier can be accessed from any part of the code, i.e., within the class and outside the class.
Protected
The protected access modifier is more protected than the public access modifier, seeing that it can only be accessed within the class and subclasses or child classes inherited from the class for which the modifier was used. We will be discussing child classes after access modifiers, so you will understand the concept of inheritance.
Private
The private access modifier is the most protected access modifier among the three main access modifiers, as it can only be accessed from within the class. Any attempt to access attributes and methods with the private access modifier would result in an error.
In the code above,
$brand is a public attribute; hence, it can be accessed from anywhere.
$colour is a protected attribute, and it can only be accessible within the class and its subclasses.
$model is a private attribute, and it can only be accessible within the Car class.
The $colour attribute is protected, which is why a subclass had to be created to access it outside the class.
The public method get_brand() allows external access to the brand attribute, and the protected method get_color() can only be accessed by classes inherited from the Car class. The private method get_model(), which can only be accessed within the Car class.
The code gives the output below:
Inheritance
Inheritance is another fundamental concept in OOP. It allows new classes to be built upon existing classes and allows these new classes to access both the attributes and methods of the old classes and also create new attributes and methods of their own. Inheritance also provides a form of security in tandem with the protected access modifier because only inherited classes can access attributes and methods protected with the protected access modifier.
The ExtendedCar class is a child of the Car class and inherits its attributes and methods.
The child class ExtendedCar adds an attribute, $model, and another method called get_model() to get the model of the car. It also introduces a method display_info() that displays the brand, colour, and model of the car from the parent class and the child class. A constructor was also created in the child class with the parent’s constructor.
Namespaces
What are Namespaces? Namespaces provide a sort of way to uniquely identify classes, functions, constants, and variables with the same names in different aspects of the code. It provides a unique identifier for these components of the same name, thereby ensuring there is no collision of names. It does this by putting these components into different scopes. Namespaces are declared using the namespace keyword, which is followed by the name of the namespace. Namespaces allow for the same name for attributes and methods.
I will be demonstrating how Namespaces can be used below:
In the code above, there are namespaces created to demonstrate how namespaces can be used in OOP to avoid name conflicts. Two namespaces were created: CarNamespace and BikeNamespace; they both contain the same name for attributes and methods. In order to declare the classes, they have to be called with the namespaces: CarNamespace for the Car class and BikeNamespace for the Bike class. The code outputs the following:
Conclusion
In this article, we learned about the concept of OOP in the PHP language. We learned about the main concepts of OOP, such as Classes and Objects, constructors and destructors, Access modifiers, inheritance, and Namespaces. Using the concepts taught in this article, developers can write reusable and maintainable code in PHP.