PHP OOP – Encapsulation

Encapsulation allows us to hide properties and methods within a class such that they are not accessible by other classes.

In PHP access modifiers are used for encapsulation, these modifiers are simply PHP keywords, to set the access permissions for class methods and variables. Some of the access modifiers can even be applied to the class itself.

A list of PHP keywords that are used as access modifiers is as follows:

ModifierDescription
publicThere are no restrictions on access. Can be accessed from anywhere, including outside the scope of the class.
privateOnly the class that defines the method/variable has access to it.
protectedOnly the class that defines it, as well as any child classes, have access to the protected method/variable.
finalMethods that are declared as final cannot be updated or overridden by a subclass.
abstractAbstract indicates that a class or method’s implementation is not defined.

Note: The default access modifier is public if no other access modifier is specified.

Which Access Modifier Should I Use When?

ModifierClassMethodVariable
publicNot ApplicableApplicableApplicable
privateNot ApplicableApplicableApplicable
protectedNot ApplicableApplicableApplicable
finalApplicableApplicableNot Applicable
abstractApplicableApplicableNot Applicable

In the next chapter, we’ll look at final and abstract modifiers, but first, let’s look at an example of other modifiers.

Access modifiers to Variables

In the below example lets have three different variables assigned three different modifiers:

  • $name is public
  • $colour is protected
  • $quantity is private

Now if we will call $colour and $quantity outside the class then it will give an error.

<!DOCTYPE html>
<html>
<body>

<?php
class Car {
  public $name;
  protected $color;
  private $quantity;
}

$Revo = new Car();
$Revo->name = 'Revo'; // As its public so it will not show error
$Revo->color = 'Balck'; // ERROR
$Revo->quantity = '2'; // ERROR
?>
 
</body>
</html>

Access modifiers to Methods

In the below example lets have three different methods for setting the value of 3 different variables assigned three different modifiers:

The first method is written without specifying the access modifier so by default it’s public.

Now if we will call $set_colour and $set_quantity outside the class then it will give an error.

<!DOCTYPE html>
<html>
<body>

<?php
class Car {
  public $name;
  public $color;
  public $quantity;

  function set_name($n) { // a public function (default)
    $this->name = $n;
  }
  protected function set_color($c) { // a protected function
    $this->color = $c;
  }
  private function set_quantity($q) { // a private function
    $this->quantity = $q;
  }
}

$Revo = new Car();
$Revo->set_name('Revo'); // OK
$Revo->set_color('Black'); // ERROR
$Revo->set_quantity('2'); // ERROR
?>
 
</body>
</html>