article

Thursday, July 25, 2013

Public, Private and Protected - PHP OOP

Public, Private and Protected - PHP OOP 

Example 
 
<?php
//Public Visibility in PHP Classes
//Public methods or variables can be accessible from anywhere. It can be accessible from using object(outside the class), or inside the class, or in child class.
class test
{
public $abc;
public $xyz;
public function xyz()
{
}
}

$objA = new test();
echo $objA->abc;//accessible from outside
$objA->xyz();//public method of the class test
?>

<?php
//Private Visibility in PHP Classes
//only be accessible withing the class. Private visibility in php classes is used when you do not want your property or function to be exposed outside the class.
Class test
{
public $abc;
private $xyz;
public function pubDo($a)
{
echo $a;
}
private function privDo($b)
{
echo $b;
}
public function pubPrivDo()
{
$this->xyz = 1;
$this->privDo(1);
}
}
$objT = new test();
$objT->abc = 3;//Works fine
$objT->xyz = 1;//Throw fatal error of visibility
$objT->pubDo("test");//Print "test"
$objT->privDo(1);//Fatal error of visibility
$objT->pubPrivDo();//Within this method private function privDo and variable xyz is called using $this variable.
?>


<?php
//Protected Visibility in PHP Classes
//useful in case of inheritance and interface. Protected method or variable can be accessible either within class or child class.
class parent
{
protected $pr;
public $a
protected function testParent()
{
echo this is test;
}
}
class child extends parent
{
public function testChild()
{
$this->testParent(); //will work because it
}
}
$objParent = new parent();
$objParent->testParent();//Throw error
$objChild = new Child();
$objChild->setChild();//work because test child will call test parent.
?>

Related Post