Access Modifiers : Public vs Private

In the last chapter we discussed chaining methods and properties, and how to use them.

Today we will learn an interesting topic which is Access Modifiers : public vs private.  From the starting of the tutorial we were using public access modifiers . The reason behind using the public access modifier is to use the public methods and property without any restriction within the class scope as well as outside the class.

Public access modifier : Methods and properties that are declared public can be accessed within the class as well outside the class. Here is an example given below.

Example : 

Private access modifier : Methods and properties that are declared private can only be accessed within the class scope. It can’t be accessed outside the class. Let’s understand this with an example.

Example : 

Output : Fatal error: Cannot access private property Test::$subject in ….

There might be one question striking in your mind that Why do we need public and private access modifiers ?

We need private access modifier in order to restrict the access to code which approach it from outside the class. Sometimes it is required to block some property and methods to be accessed outside the class. In later tutorial you will easily understand this if it is not clear as of now. Just simply remember that private access modifier is used to restrict the access to property and methods from outside the class. While methods and property which are declared as public can be accessed outside the class as well within the class.

 

Leave a Reply

Your email address will not be published. Required fields are marked *