PHP Tutorial PHP Advanced PHP References

PHP - Encapsulation



Access Specifier

Before understanding the concept of encapsulation, it is important to understand the concept of access specifier. Access specifiers defines the access type of the member (properties and methods) of the class and there are three types of access specifier in PHP.

  • public: members of the class are accessible from everywhere. It is also default access specifier.
  • protected: members of the class are accessible within the class and by derived classes.
  • private: members of the class are ONLY accessible within the class.

Example:

In the example below, a class called person is created which has a private property called name. When it is accessed in the program, it raises an exception because it is a private property and it can not be accessed outside the class in which it is defined.

<?php
class person {
  private $name = "John";
};

$p1 = new person();
echo $p1->name; 
?>

The output of the above code will be:

PHP Fatal error:  Uncaught Error: Cannot access private property person::$name

Encapsulation

Encapsulation is a process of binding the properties and methods together in a single unit called class. It is aimed to prevent the direct access of properties and available only through methods of the class. Data encapsulation led to the important concept of data hiding in object-oriented programming also known as Data abstraction. Data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

Data Encapsulation steps:

  • Declare each property private.
  • Create public set method for each property to set the values of properties.
  • Create public get method for each property to get the values of properties.

In the example below, public set and get methods are created to access private properties name and age of class person.

<?php
class person {
  private $Name;
  private $Age;
  //method to set the value of Name
  public function setName($name) {
    $this->Name = $name;
  }
  //method to get the value of Name
  public function getName() {
    return $this->Name;
  }
  //method to set the value of Age
  public function setAge($age) {
    $this->Age = $age;
  }
  //method to get the value of Age
  public function getAge() {
    return $this->Age;
  }
};

$p1 = new person();

//set the name and age
$p1->setName("John");
$p1->setAge(25);
//get the name and age
echo $p1->getName()." is ".$p1->getAge()." years old."; 
?>

The output of the above code will be:

John is 25 years old.