Access Specifiers in PHP
Advertisements
Access Specifiers in PHP
There are three types of Access Specifiers available in PHP, Private, Protected and Public.
Public: Class members declared public can be accessed everywhere.
Protected: Class members declared protected can be accessed only within the class itself and by inheriting classes.
Private: Class members declared as private may only be accessed by the class that defines the member.
Syntax
<?php class MyClass { public $public = 'Public'; protected $protected = 'Protected'; private $private = 'Private'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; } } $obj = new MyClass(); echo $obj->public; // Works echo $obj->protected; // Fatal Error echo $obj->private; // Fatal Error $obj->printHello(); // Shows Public, Protected and Private /** * Define MyClass2 */ class MyClass2 extends MyClass { // We can redeclare the public and protected properties, but not private public $public = 'Public2'; protected $protected = 'Protected2'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; } } $obj2 = new MyClass2(); echo $obj2->public; // Works echo $obj2->protected; // Fatal Error echo $obj2->private; // Undefined $obj2->printHello(); // Shows Public2, Protected2, Undefined ?>
Google Advertisment