In PHP there are 6 keywords that is more important for any developer who use Object Oriented Programming for building PHP web pages.
The first 3 keywords are related to each other in a manner of how they operate in providing access to the properties and methods inside the class they are used.
Private, Public and Protected
As shown in the above image, private is at the core of the accessibility. It means that private properties (i.e. variables) or functions inside a class can only be access inside the class that defines it. It cannot be accessed by the instance (i.e. object) of the class or by the instance of the classes that inherits this class as its base class. You also cannot access them via the class name with the scope resolution operator style (
Protected is at the next level of the private accessibility. The properties and function with protected visibility can be accessed only within the class that defines it and the class that extends it i.e. the class that inherits it. Only the inherited class can access can access those properties and functions.
Public visibility properties and functions can be accessed by any object of the class and also the class that inherits it.
Static keyword for Properties
If a property (i.e. variables) or functions of class is declared static then that property is common to all objects. Its value is not object dependent, but class dependent. For example, consider a variable
$tax declared inside the
Electronics class. There may be any number of items which is an object of the
Electronics class. But for all the item objects, the value of
$tax variable will be the same. If the value of the
tax variable is changed by any of the object, then it will reflect to all the other objects. Simply put, static variable is like a shared variable
Static keyword for Functions
If a function is declared static, then like the static property the function is class dependent and not object dependent. There are rules for using the static function.
- It can be accessed using
$thiskeyword cannot be used inside the static function since it is not object dependent. Because
$thisrepresents a specific instance of the class.
If a property or function is defined with
final keyword, then the property value cannot be changed and if it is a function, that function signature cannot be overridden or changed.
Class declared as
abstract cannot have any instance i.e. object declaration. Functions declared as abstract must be placed inside the abstract class only. Class containing a single abstract method should be declared as abstract. Abstract class is used for inheritance.