In professional software design, permitting outside scripts to freely alter the internal variables of an object leads to catastrophic bugs, security vulnerabilities, and data corruption. Encapsulation is the fundamental OOP principle of restricting direct access to an object's internal components. In PHP, this control is enforced through Visibility Access Modifiers: public, protected, and private.
| Access Modifier | Inside Same Class | Inside Child Subclasses | Outside Object Scope |
|---|---|---|---|
public |
YES | YES | YES (Anywhere) |
protected |
YES | YES (Inherited) | NO (Blocked) |
private |
YES | NO (Blocked) | NO (Blocked) |
By declaring properties private and providing public getter and setter methods, you can enforce strict business validation rules:
<?php
class StudentRecord {
private string $name;
private float $gpa; // Protected from unauthorized direct tampering
public function __construct(string $name, float $initialGpa) {
$this->name = $name;
$this->setGpa($initialGpa); // Validate via setter
}
// Getter for GPA (Read-Only access)
public function getGpa(): float {
return $this->gpa;
}
// Setter for GPA (Enforces validation)
public function setGpa(float $newGpa): void {
if ($newGpa < 0.0 || $newGpa > 4.0) {
throw new InvalidArgumentException("GPA must be between 0.0 and 4.0.");
}
$this->gpa = $newGpa;
}
}
$student = new StudentRecord("Deepa", 3.8);
echo "Current GPA: " . $student->getGpa() . "<br>";
// Valid update:
$student->setGpa(3.95);
echo "Updated GPA: " . $student->getGpa() . "<br>";
// Invalid attempt: Direct access triggers Fatal Error
// $student->gpa = 5.0; // Fatal Error: Cannot access private property
?>
High-Frequency Exam Question:
Q: What is the default visibility of properties and methods in PHP if no modifier is specified?
A: In PHP, methods declared without an explicit modifier (e.g. function display()) default to public. Properties in modern PHP must have an explicit visibility modifier; omitting it causes a syntax error.
Exercise 37.1: Create a User class with a private $passwordHash property. Provide a setPassword($plain) method that hashes the password with password_hash(), and a verifyPassword($plain) method.
Exercise 37.2: Create a base Employee class with a protected $salary property, proving that an extended Manager class can access it while external code cannot.