PHP 5 Access Specifiers
Access Specifiers
Encapsulation is the key feature of the Object Oriented Programming paradigm, You can achieve encapsulation with the help of access specifier. Access specifier specifies the level of the access of properties and methods.
There are three Access Specifiers in PHP private, public protected. These keywords help you to define how methods and properties will be accessed by the user.
Private
Private: Data member and member function that declared as private are not allowed to be called from outside the class. However, you can easily access these properties within the class shown in the example.
Example
<?php class Computer { private $name = 'Sony Vaio'; function display() { echo $this->name; } } $obj = new Computer(); echo $obj->display(); // Works //echo $obj->name; Fatal error: //Cannot access private property Computer::$name ?>
Output
Sony Vaio
Public
Public: Any Data member and member function that declared as public or without any modifier are allowed to access these properties from inside or outside the class.
Example
<?php class Computer { private $name; function setName($brand) { $this->name=$brand; } function display() { echo $this->name; } } $obj = new Computer(); $obj->setName("Sony Vaio"); echo $obj->display(); ?>
Output
Sony Vaio
Protected
Protected: It is a special type of modifier. If any property or method is declared as protected, you can only access these properties within the class and its subclass.
Example
<?php class Computer { protected $name = 'Sony Vaio'; function display() { echo $this->name."
"; } } class Laptop extends Computer { protected $name = 'Dell'; function display1() { echo $this->name."
"; } } $obj=new Computer(); $obj->display(); //$obj->protected; //Fatal Error //echo $obj2->protected; // Fatal Error $obj2 = new Laptop(); $obj2->display(); $obj2->display1(); ?>
Output
Sony Vaio
Dell
Dell
Complete Example of PHP 5 Access Specifiers
<?php class Country { public $a = "India"; private $b = "UK"; function display() { echo "Parent class"."
"; echo $this->a."
"; echo $this->b."
"; } } class Test extends Country { function display() { echo "Child class"."
"; echo $this->a."
"; // echo $this->b; Not accessible private member } } $obj=new country(); $obj->display(); $obj=new Test(); $obj->display(); ?>
Output
Parent class
India
UK
Child class
India
In the above example, all three Access Specifiers are used for better understanding.