Encapsulation in php with example

Encapsulation in PHP is the restriction of access to objects.

With Encapsulation You have control to allow which property or method to be visible outside the class.

To apply Encapsulation add a public, private, or protected keyword to the specific method or property.

  1. public       can be accessed anywhere
  2. private     can be accessed just within the same class
  3. protected can be accessed just within the class and other classes derived from that class

look at this example we will create a User class. User class will have a Private $name ,Public function editUser() and Public function getName()

<?php

class User{
   private $name;
   public function editUser($name){
      // .. code
      $this->name=$name;
   }
   public function getName(){
      // .. code
      return $this->name;
   }

}
$user = new User();
     $user->editUser('Qandeel');
echo $user->getName();

as you can see we can access the private property using the editUser method and get the user name using the getName method.

You will get "Fatal error: Uncaught Error: Cannot access private property User::$name"  when you are trying to access the Private Property direct.