In this tutorial, you shall learn about Encapsulation in PHP, an Object Oriented Programming concept, how it can be implemented in PHP programs, with examples.
Encapsulation
Encapsulation is the ability of an object to keep its properties and methods private or protected from outside the class for reading or writing.
In PHP, encapsulation is achieved through the use of classes, which allow you to define properties and methods with different access levels as given in the following.
- public: properties and methods can be accessed from anywhere, both inside and outside the class.
- protected: properties and methods can only be accessed from within the class and its subclasses.
- private: properties and methods can only be accessed from within the class itself.
Therefore, based on the requirement we define some properties and methods of the class as public, which can be accessed from outside the class. Some properties and methods of the class as protected, which can be accessed from within the class or its sub-classes. And some properties and methods of the class as private, which can be accessed from within the class itself.
Example
In the following example, we define a class Person
. It has two properties $name
and $age
. These properties are defined private, therefore, these properties cannot be accessed directly from outside the class. So, to read or update these properties, we define methods with public access.
We have four methods defined in this class. getName()
and getAge()
are used to read the properties, while setName()
and setAge()
are used to update the values of the properties. With these methods we can restrict the access, or limit how the data is read from or written to these properties.
For example, look at setAge()
method. We set the $age
property only if the age is valid. If the age is not valid, we throw an Exception.
class Person {
private $name;
private $age;
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getAge() {
return $this->age;
}
public function setAge($age) {
if ($age < 0) {
throw new Exception('Age cannot be negative');
}
$this->age = $age;
}
}
Now, let us write some code to create an object for Person, and access the properties via methods.
PHP Program
<?php
class Person {
private $name;
private $age;
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getAge() {
return $this->age;
}
public function setAge($age) {
if ($age < 0) {
throw new Exception('Age cannot be negative');
}
$this->age = $age;
}
}
$person1 = new Person();
$person1->setName('Arjun');
$person1->setAge(25);
print_r("Name : " . $person1->getName() . "<br>");
print_r("Age : " . $person1->getAge() . "<br>");
?>
Output
Conclusion
In this PHP Tutorial, we learned what Encapsulation of Object Oriented Programming is, how to implement Encapsulation in PHP, and how to encapsulate properties or methods of a class.