← Back to Chapters

PHP OOP Access Modifiers

? PHP OOP Access Modifiers

? Quick Overview

Access Modifiers in PHP Object-Oriented Programming define how and where class properties and methods can be accessed.

? Key Concepts

  • public – Accessible from anywhere.
  • protected – Accessible within the class and its child classes.
  • private – Accessible only within the declaring class.

? Syntax & Theory

Access modifiers help implement encapsulation by restricting direct access to class data and enforcing controlled interaction through methods.

? View Code Example
// Demonstrating public, protected, and private access modifiers
<?php
class Student {
public $name;
protected $rollNo;
private $marks;

public function __construct($name, $rollNo, $marks) {
$this->name = $name;
$this->rollNo = $rollNo;
$this->marks = $marks;
}

public function getMarks() {
return $this->marks;
}
}

$student = new Student("Rahul", 101, 95);

echo $student->name;
echo $student->getMarks();
?>

? Live Output / Explanation

The name property is accessible directly because it is public. The marks property is private, so it can only be accessed using the getMarks() method.

? Interactive Concept

Try changing access modifiers and observe how PHP throws errors when visibility rules are violated.

? Use Cases

  • Protect sensitive data like passwords.
  • Expose only required methods to users.
  • Support inheritance with controlled access.

? Tips & Best Practices

Use private for strict encapsulation, protected for inheritance, and public only when external access is required.

? Try It Yourself

Create an Employee class with public, protected, and private properties and test accessibility using getter methods.