oursolutionarchitectoursolutionarchitect

PHP | Access Specifiers


In the PHP each and every property of a class in must have one of three visibility levels, known as public, private, and protected.
 

  • Public: Public properties can be accessed by any code, whether that code is inside or outside the class. If a property is declared public, its value can be read or changed from anywhere in your script.
  • Private: Private properties of a class can be accessed only by code inside the class. So if we create a property that’s declared private, only methods and objects inside the same class can access its contents.
  • Protected: Protected class properties are a bit like private properties in that they can’t be accessed by code outside the class, but there’s one little difference in any class that inherits from the class i.e. base class can also access the properties.

Generally speaking, it’s a good idea to avoid creating public properties wherever possible. Instead, it’s safer to create private properties, then to create methods that allow code outside the class to access those properties. This means that we can control exactly how our class’s properties are accessed. 
Note: If we attempt to access the property outside the class, PHP generates a fatal error.
PHP Access Specifier’s feasibility with Class, Sub Class and Outside World :
 

Class Member Access Specifier Access from own class Accessible from derived class Accessible by Object
Private Yes No No
Protected Yes Yes No
Public Yes Yes Yes