quick links

What is visibility or accesibility in oops? or what is public, protected and private in oops?

There are 3 types of visibility to control methos and variable in php.

  • Public
  • Protected
  • Private

Public: Public methos and variable access by 1) The same class. 2) The classes that inherit the class. 3) We careate object of this class and use public method and variable.

class GrandPa {
public $name='Mark Henry'; // A public variable
}
class Daddy extends GrandPa // Inherited class {
function displayGrandPaName() {
return $this->name; // The public variable will be available to the inherited class
}
}

//Inherited class Daddy wants to know Grandpas Name
$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Prints 'Mark Henry'

//Public variables can also be accessed outside of the class!
$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Prints 'Mark Henry'

Protected: Protected methos and variable access by 1) The same class. 2) The classes that inherit the class. 3) But we can't access by object of class in which it define.

class GrandPa {
protected $name = 'Mark Henry';
}
class Daddy extends GrandPa {
function displayGrandPaName() {
return $this->name;
}
}
$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Prints 'Mark Henry'

$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Results in a Fatal Error

Private: Private methos and variable access by 1) The same class. 2) Also we can't aceess it by object of same class and inherit class.

class GrandPa{
private $name = 'Mark Henry';
}
class Daddy extends GrandPa{
function displayGrandPaName(){
return $this->name;
}
}

 

About Us

Joomla Web Solution

We love working with PHP, HTML5, CSS3, jQuery and the most-loved content management framework in the world, Joomla!

LIKE US ON FACEBOOK