There are three type of visibility scope:
- Public
- Private
- Protected
PUBLIC:
Variable or function of public scope can be accessed throughout the program.
PRIVATE :
Variable or function of private scope can be accessed only with in the class they are declared.
PROTECTED:
Variable or function of protected scope can be accessed only by its subclass and derived class.
<?php
/**
* Define ClassA
*/
class ClassA
{
public $a = 1;
protected $b = 2;
private $c = 3;
function detail()
{
echo $this->a;
echo $this->b;
echo $this->c;
}
}
$obj = new ClassA();
echo $obj->a; // Works
echo $obj->b; // Fatal Error
echo $obj->c; // Fatal Error
$obj->detail(); // Shows Public, Protected and Private
/**
* Define ClassB
*/
class ClassB extends ClassA
{
// We can redeclare the public and protected method, but not private
protected $b = '4';
function detail()
{
echo $this->a;
echo $this->b;
echo $this->c;
}
}
$obj2 = new ClassB();
echo $obj2->a; // Works
echo $obj2->b; // Fatal Error
echo $obj2->c; // Undefined
$obj2->detail(); // Shows Public, Protected2, Undefined
?>
0 Comment(s)