PHP Access Modifiers
Access modifiers in PHP control the visibility of class properties and methods. There are three types of access modifiers:
- public: Properties and methods are accessible from anywhere.
- protected: Properties and methods are accessible within the class and by derived classes.
- private: Properties and methods are accessible only within the class itself.
Example of Access Modifiers
<?php
class Person {
public $name;
protected $age;
private $ssn;
public function __construct($name, $age, $ssn) {
$this->name = $name;
$this->age = $age;
$this->ssn = $ssn;
}
public function getDetails() {
return "Name: " . $this->name . ", Age: " . $this->age;
}
}
$person = new Person("Alice", 30, "123-45-6789");
echo $person->getDetails(); // Accessible
// echo $person->age; // Not accessible (protected)
// echo $person->ssn; // Not accessible (private)
?>
Output:
Name: Alice, Age: 30
Explanation: This example demonstrates the use of access modifiers in PHP. The name
property is public and accessible, while the age
property is protected and the ssn
property is private, making them inaccessible from outside the class.