Monday, March 30, 2009

Public, protected and private scope in php

Prepend the public or private or protected keyword before a variable declaration define the scope of the variable.

If the variable is declared as public then that variable can be accessed from anywhere.

If the variable is declared as proteced then that variable can be accessed from parent class and inherited classes and the class that define the variable.

If variable is declared as private then it is only available within the class that defines it.

If neither public/private/protected keyword are specified in declaration then by default the method/variable becomes public.

Below is an example with these keywords.

<?php
class BaseClass{
public $publicVar='Public Variable ';
protected $protectedVar='Protected Variable ';
private $privateVar='Private Variable';

public function display(){
echo $this->publicVar;
echo $this->protectedVar;
echo $this->privateVar;
}
}

class DerivedClass extends BaseClass{
protected $protectedVar2='Protected Variable 2';


function display(){
echo $this->publicVar;
echo $this->protectedVar;
echo $this->protectedVar2;
echo $this->privateVar;
}
}
$baseInstance=new BaseClass();
echo $baseInstance->publicVar; //It will work as public
echo "<br />";
//echo $baseInstance->protectedVar; //Fatal error as protected can be accessed within base and derived class.
//echo "<br />";
//echo $baseInstance->privateVar; //Fatal error as private can be accessed within it's own class
//echo "<br />";
echo $baseInstance->display(); //show all three as display is the method of the class.
echo "<br />";

$derivedInstance=new DerivedClass();
echo $derivedInstance->display(); //private variable of base class will not be shown.
?>

And the output is,

Public Variable
Public Variable Protected Variable Private Variable
Public Variable Protected Variable Protected Variable 2

Related Documents
http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html
http://arjudba.blogspot.com/2009/03/autoloading-objects-in-php.html
http://arjudba.blogspot.com/2009/03/constructors-and-destructors-in-php.html

No comments:

Post a Comment