PHP supports both procedural and Object-Oriented programming. Object-Oriented methodologies will be useful and effective while working with complex or huge-size projects.
It helps to compartmentalize the project-based domains and programming layers to make it easy to handle. In this tutorial, we are going to see some of the important OOPS features supported by PHP like Class, Object, Encapsulation, Inheritance and more. I have described these features with simple examples.
The class is a programming block structure that contains its own properties and methods to process the domain functionalities. We can create instances for a class to access its properties and method.
The following example code shows a Mobile() class containing the properties and methods. In this example, I have specified an access specifier for the class properties and methods. These access specifiers are used to restrict the visibility of the class properties and methods.
<?php
class Mobile
{
private $premiumModal = "iPhone";
public function getPrimiumModal()
{
return $this->premiumModal;
}
}
?>
Objects or Instances can be created for a class to access the class components. The below PHP code shows how to create an object to the Mobile() class and it is used to access the class components.
<?php
class Mobile
{
private $premiumModal = "iPhone";
public function getPrimiumModal()
{
return $this->premiumModal;
}
}
$object = new Mobile();
echo "<b>Premium Modal:</b> " . $object->getPrimiumModal() . "<br/>";
?>
The Constructor is a class function called automatically when an instance is created for that class. The Destructor is a function that is invoked when the class instance is destroyed.
In PHP, the constructor and the destructor are defined by using the magic functions __construct() and __destruct() respectively. The following code shows an example of the class constructor used to initialize its private property.
<?php
class Mobile
{
private $modal;
function __construct()
{
$this->modal = array(
"iPhone",
"Samsung Galaxy",
"MotoG"
);
}
function printAllModal()
{
foreach ($this->modal as $modal) {
print $modal . "<br/>";
}
}
}
$object = new Mobile();
echo "<b>All Modals:</b><br/>";
$object->printAllModal();
?>
There are three types of inheritance single, multiple and multi-level inheritance. PHP supports single and multi-level inheritance. It will not support multiple inheritances.
That is, A class can extend only one parent class. To overcome this limitation, PHP provides the Traits concept which allows us to use functions of one class in one or more classes. We have a detailed article about PHP inheritance with more examples.
Since properties and methods of the objects are enclosed with the class container in an abstract manner, any code from outside can not access the class, unless otherwise by using objects of that class. In this way, the properties are encapsulated.
good