What is Visibility?
Visibility within a class is basically an option that allows you to give
different user permission levels to functions and variables. There are 3
different options for visibility: Private - can only be accessed within that
class Protected - can only be accessed within that class and child classes
Public - can be accessed by all code
By default,
PHP uses Public in class programming, but it is always a good idea to declare
visibility to give your coding easier viewing to others.
The visibility
option goes before the variable name of before the function definition, as
shown below:
<?php Class someClass {
public $var1 = "Hi, I'm public";
protected $var2 = "Hi, I'm protected";
private $var3 = "Hi, I'm private >:D";
protected $var2 = "Hi, I'm protected";
private $var3 = "Hi, I'm private >:D";
public function sayPublic() {
echo("I'm public!");
}
protected function sayProtected() {
echo("I'm protected!");
echo("I'm protected!");
}
private function sayPrivate() {
echo("I'm private >:D !");
echo("I'm private >:D !");
}
} ?>
So, we can
call anything that is public without problem, being able to call sayPublic()
and $var1 and output them outside of the class.
Now, if we
call the private variable, we will get this error in PHP:
Fatal
error: Cannot access private property someClass::$var in
C:\Server\www\Visibility\PrivateExample.php on line 17
and a private
function called will result in:
Fatal
error: Call to private method someClass::sayPrivate() from context '' in
C:\Server\www\Visibility\PrivateExample.php on line 17
now the same
kind of error will occur with a protected variable and function as well, just
saying "Call to protected method" or "Cannot access protected
property".
Now, what we
can do though is echo out and return private and protected variables in public
functions:
<?php Class someClass {
public $var1 = "Hi, I'm public"; protected $var2 = "Hi, I'm protected"; private $var3 = "Hi, I'm private >:D";
public function sayPrivateVar() {
echo $var3;
}
public function sayProtectedVar() {
echo $var2;
}
} ?>
We can, as I
said before, call child classes to use the functions as well:
<?php Class someClass {
protected function sayHi() {
$this->var = "Hello";
retun $this->var;
}
}
Class someExtendedClass extends someClass {
public function sayHi($someName) {
echo(parent::sayHi());
echo(" $someName");
}
}
?>
?>
Conclusion:
Private members can only be accessed from inside the
class itself.
Protected members can only be accessed from inside the class it self and its child classes.
Public members can be accessed from anywhere - outside the class, inside the class it self and from child classes.
class itself.
Protected members can only be accessed from inside the class it self and its child classes.
Public members can be accessed from anywhere - outside the class, inside the class it self and from child classes.
Post a Comment