Introduction
Object-oriented programming is followed by many languages, including C++, Java, python. This article will first give you a basic understanding of OOP in PHP, then discuss classes and objects in detail. We will also see a few illustrations implementing OOP in PHP.
What is OOP in PHP?
The object-oriented programming is about wrapping data and related functions in classes. While in procedural programming, data is open and accessible to all, and we write functions to operate on them. We cannot add more properties with ease, making it a heavy task for the developer. Languages like C, Fortran, BASIC follow such approaches.
OOP follows four principles: Encapsulation, Polymorphism, Data abstraction and inheritance.
Encapsulation
It refers to the bundling of data and functions operating on the same data. This keeps a separation between all of the different types of data present in the program. Data hiding can be done while encapsulating code with the help of public, private keywords.
For example
class User{
private $id;
private $pwd;
public function getId(){
return $id;
}
}
Here we created private fields which are not directly accessible but only with the public function getId it is accessible. Password cannot be accessed by anyone.
Polymorphism
It simply means being able to exist and function in multiple forms. In PHP, interfaces are used to implement polymorphism. Common functionality is defined in the interface and implemented in multiple classes. In the example below, calcArea can be used by both circle and rectangle.
For example
interface common{
public function calcArea();
}
class Circle implements common {
$radius;
public function __construct($radius){
$this->radius=$radius;
}
public function calcArea(){
$area=$this->radius*2*3.14;
return $area;
}
}
Abstraction
This concept allows for hiding the implementation details of the class and displays only the functionality. Abstraction can be achieved by using abstract classes, and interfaces. For example, we can declare an abstract class named ‘Car’ which can be extended by various car companies like Audi, Mercedes implementing the same common functionality as mentioned in the abstract class.
Inheritance
Classes can use certain common attributes from another class. For example, a student, a teacher comes under a common class of users, and so both need to inherit userId from their parent “staff”. This concept of inheriting common fields from one common class is termed as inheritance.