the visibility keyword is used to define where the variable is available:
A property or method can be declared adding the visibility(public,private, protect) keyword in front of its declaration.
<?php class MyClass { public $public = 'Public'; private $private = 'Private'; function printHello() { echo $this->public; echo $this->private; } } $obj = new MyClass(); echo $obj->public; // Works echo $obj->private; // this is invalid - will throw a Fatal Error $obj->printHello(); // Shows Public, Protected and Private
A method declared without a visibility keyword will be public
by default.
Property cannot be declared without a visibility keyword.
Otherwise it will throw a fatal error
Parse error: syntax error, unexpected '$color' (T_VARIABLE), expecting function (T_FUNCTION) or const (T_CONST)
<?php class House { $color = "red"; } ?>
Visibility realize the encapsulation in PHP OOP, keep private properties private, prevent them be accessed from outside the class.
Meanwhile, To access a private/protected property or method, usually define a public method inside the class to access the property/method indirectly.
In this public method, we can validate the data before modify it. If the property data can be modified directly, we can not validate and restrict the data setted by the caller who use this class.
<?php class House { private $color; private $allowedColors = [ 'red', 'green', 'blue' ]; public function getColor() { if ($this -> color) { return $this -> color; } else { return 'The color is not set.'; } } public function setColor($color) { // validate the data color $color = strtolower($color); if ( in_array( $color, $this->allowedColors ) ) { $this -> color = $color; return "Setting color successfully."; } else{ return "The color is not allowed."; } } } $house = new House(); // echo $house -> color; // Fatal Error, Directly access is not allowed echo $house -> setColor('blue'); echo $house -> getColor(); ?>
On the other hand: Visibility realize the abstraction in OOP.
Only a small set of public methods can be called by other class.
The internal implementation details should be hidden. So we keep them private.
For example, we interact with phone by using only a few buttons. We don’t have to know how it work. The actions(under) under the hood is not accessible(private).