PHP OOP Access Modifiers

PHP Tutorial

PHP OOP Access Modifiers (public, private, protected)

PHP OOP Access Modifiers control the visibility of properties and methods in a class.

1. Types of Access Modifiers in PHP

ModifierAccessible Inside ClassAccessible Outside ClassAccessible in Child Class
public YesYes Yes
private Yes No No
protected Yes NoYes

 public (open for all)

Anything public can be accessed from anywhere.

 Example:


 


 private (only inside same class)

Private properties/methods cannot be accessed from outside or by child classes.

 Wrong (will cause error):


 Correct:

Access using a public method:


 


 protected (inside class + child class)

Protected can be accessed from:

  •  same class
  •  inherited (child) classes
  •  NOT accessible from outside

Example:


 


 Full Example: All 3 Modifiers Together


 


 Why Access Modifiers Are Important?

  •  Improve security
  •  Prevent accidental changes
  •  Control how data is accessed
  •  Make code clean and professional
  •  Essential for real OOP projects 
  •  Used heavily in Laravel

 Summary Table (Easy to Remember)

ModifierMeaning
publicAnyone can access
privateOnly inside the class
protectedClass + child subclass

You may also like...