Thursday, February 1, 2018

Access Control Modifiers in PHP

Access Modifiers 

Access Modifiers are keywords that control visibility of class properties and methods. In PHP there are three of them:

1. Private 

2. Protected 

3. Public 

Let’s describe Mindi in terms of her own class and let’s say that Mindi has a tattoo on her wrist. We could put it in PHP terms like this:

When we do it this way, the tattoo is public by default. That means it can be seen anywhere in the program. It's the same as writing it as:

Class mindi {

Public $ tattoo_location

This means class Billy or class Alex or class Dad can all see Mindi's tattoo because it has public visibility which is set by a public access modifier.

Now let's say Mindi instead has a tattoo that she doesn't want class mom or class dad to know about but wants to show off to her friends. She has this tattoo on her back so she can display it wearing a bikini top.

Class mindi {

Protected $tattoo_location;

Protected function setlocation () {}


Now Mindi can wear her bikini top around her friends and not her mom or dad. We can describe this in PHP by extending an invitation to the people she wants to show it to by using the extends key word:

Since all of these classes extend class Mindi, they can see her tattoo. This is inheritance and all of these classes that extend Mindi are part of her inheritance hierarchy. Now let's say she has her tattoo in a more intimate place (use your imagination) and she only wants her boyfriend Billy to see it and no one else. In PHP terms:

Class mindi {

Private tattoo_location;

Private setlocation ( ) { }

Private letbillysee ( ) { }


So to summarize the three PHP access Modifiers in a more formal way:


restricts the access to the class itself. Only methods that are part of the same class can access private members. Let’s look at an example below:

The reason why data members are declared private is to avoid the outside programs to unintentionally modify the values without necessary validation. If you make a data member private you should provide public getter/setter methods to access the value of this data member. The access modifier


Allows the class itself and all of it’s subclasses to access the data members and member functions. Global access is denied.


means that any code can access the member by its name.

Now back to my previous point about object-oriented principles being “global” in the way a developer should think of them. I used Mindi's tattoo to explain access modifiers but I also had to demonstrate encapsulation and inheritance in order to do so. Inheritance and Encapsulation are really just ways of regulating the ability of an object defined that is defined by a class.


Please comment and follow this site blog inbox