|
VisibilityThe visibility of a property, a method or (as of PHP 7.1.0) a constant can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inheriting classes. Members declared as private may only be accessed by the class that defines the member. Property VisibilityClass properties must be defined as public, private, or protected. If declared using var, the property will be defined as public.
Example #1 Property declaration
<?php
Method VisibilityClass methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
Example #2 Method Declaration
<?php Constant VisibilityAs of PHP 7.1.0, class constants may be defined as public, private, or protected. Constants declared without any explicit visibility keyword are defined as public.
Example #3 Constant Declaration as of PHP 7.1.0
<?php Visibility from other objectsObjects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects. Example #4 Accessing private members of the same object type
<?php The above example will output: string(5) "hello" Accessed the private method. |