Setting PHP Access Modifiers to Methods, Properties Solid Examples

In this tutorial covers the basic idea of the accessibility of methods and properties in PHP, We have learned OOP basics in previous tutorial. At this point, we are going to learn about usage of methods and properties in different perspectives. You can deny access to the members of a class or object with the PHP access modifiers, there are three modifiers public, private, and protected. Let’s look at these modifiers usage,

  • public  means accessible to all
  • private means accessible in the same class
  • protected means accessible in the same class and classes derived from that class

How does public work in PHP

public is a very common modifier, which enables unrestricted access for all. Besides PHP’s default access modifier also. You can use public keyword to initialize unrestricted methods or properties. (Keywords are predefined words those have special meaning in PHP). Public encourages explicitly declaration of methods and properties. Let me paint an example


Solid Example for Public Access PHP

This code works, printing the name of the student stored internally in the object. Here properties and methods are treated as public access modifier. if you observe the below example php program, it does not show any restriction for methods and properties.

php access modifiers


Private Access Modifier

private keyword is used to represent private methods and properties. When you make a member private, you can’t access it outside the class.  Let me paint an example for private access.

php access modifiers private

Cannot access private property Company::$tax

You can see the example output in the above figure, as you can see you get a fatal error message because the property $tax is private.

Private method in PHP

But this code isn’t  going to work, because you are trying to call show_tax() method outside the object.

Protected Access 

Using the private keyword makes class members accessible only in the class, they are declared in, and any derived class from that class.