Home Tutorials Visibility

Visibility

  previous next
March 08, 2009 by Victor    

Another interesting feature of object oriented programming is visibility, meaning that you can hide code in a class restricting its use. This applies to methods as well as to variables. The available options are:

  • public, the property or method is fully accessible from anywhere.
  • private, the property or method is accessible only from within the class.
  • protected, the property or method is accessible from within the class and any child classes.

These constructs are called access modifiers and the default access modifier, in case you don't declare one, is public.

Just play a bit with the following code.

<?
class User 
{
    var $name;
 
    function __construct($newname) 
    {
       $this->name = $newname;
    }
 
    public function getname1() { return $this->name; }
    protected function getname2() { return $this->name; }
    private function getname3() { return $this->name; }
} 
 
class Admin extends User
{
    var $mobile;
 
    function __construct($newname,$newmobile)
    {
       $this->name = $newname;
       $this->mobile = $newmobile;
 
       print $this->getname1();
       print $this->getname2();
       # print $this->getname3(); Fatal Error
    }
}
 
$harris = new Admin("Steve Harris","9600888888");
print $harris->getname1();
#print $harris->getname2();  Fatal Error
#print $harris->getname3();  Fatal Error
?>

Add comment


Security code
Refresh