There are many programming languages that supports visibility (not necessarily using the same name) such as C++.
PHP introduced visibility in version 7.1.0 for a constant too. So, you can define a visibility for a property, a method or a constant.
The visibility can be defined by prefixing the property declaration with a specific keyword. There are 3 types of keywords available for visibility control.
- public sets the visibility to public.
- Members can be accessed anywhere in the file.
- protected sets the visibility to class itself and the classes from that class.
- Members can be accessed inside the parent or child class.
- private sets the visibility to the class itself.
- Members can not be accessed anywhere else other than the class defining them, not even by child classes.
members = a property, a method or a constant
You MUST define class properties as public, protected or private. Even if you use ar to declare a property, the visibility will be defined as public.
Here’s a really simple example from PHP official docs:
public; echo $this->protected; echo $this->private; } } $obj = new MyClass(); echo $obj->public; // Works echo $obj->protected; // Fatal Error echo $obj->private; // Fatal Error $obj->printHello(); // Shows Public, Protected and Private ?>
The code above will result in Fatal Error unless you remove the line that gives you Fatal Error.
You can redeclare the protected and public properties, but you can not redeclare private properties inside a class methods.
Let’s define another class extending the first one:
public; echo $this->protected; echo $this->private; } } $obj2 = new MyClass2(); echo $obj2->public; // Works echo $obj2->protected; // Fatal Error echo $obj2->private; // Undefined $obj2->printHello(); // Shows Public2, Protected2, Undefined ?>
The same visibility rules applies to a method or a constant as well.
class examples Global private property protected public visibility