PHP: Access control modifiers
One of the fundamental principles in OOP(Object Oriented Programming) is ‘encapsulation‘. The idea is that you create cleaner and better code, if you restrict access to the data structures (properties) and methods in your objects.
The access modifier is the most important feature of the OOP language and it is used to restrict the function and classes to be accessed. In PHP, there are some keywords representing these access control modifiers. These keywords will be added with PHP classes and its members (methods and variables).
You can restrict access to class properties using ‘access modifiers’. There are mainly 3 access modifiers:
Public: This variable or method can be used from anywhere in the script.This is the default access modifier.Properties declared as ‘public’ have no access restrictions, meaning anyone can access them.
Note: When you declare a property with the ‘var’ keyword, it is considered ‘public’.
Private: When you declare a property as ‘private’, only the same class can access the property i.e variable or function can only be used by the object it is part of; it cannot be accessed elsewhere
Protected: When a property is declared ‘protected’, only the same class and classes derived from that class can access the property(this can be done using inheritance). We can say variable or function can only be used by the object it is part of, or descendents of that class.
There are some other special keywords you can place before a class, a class function definition, or a class variable to alter the way PHP works with it – here’s are the list, along with what each of them does..
Final: This variable or function cannot be overridden in inherited classes.
Abstract: This function or class cannot be used directly – you must inherit from them first.