PHP Access Modifiers
An access modifier (also called a visibility keyword) decides where a property or method can be used from.
PHP offers three of them:
public- available from anywhere; this is the defaultprotected- available inside the class and inside classes derived from itprivate- available ONLY inside the class that defines it
Note: Leave the modifier out and PHP treats the property or method as public.
Public Access Modifier
Marking a property or method public means any code can reach it, inside or outside the class.
In the next example, code outside the class can use both the $name property and the get_details() method.
Public Example
Code outside the class sets a public property and calls a public method:
Output: PHP script
<?php
class Fruit {
public $name;
public function get_details() {
echo "Name: " . $this->name . ".";
}
}
$apple = new Fruit();
$apple->name = "Apple"; // Can be accessed directly
$apple->get_details();
?>
Private Access Modifier
private is the strictest modifier: only code inside the defining class can touch the property or method.
In the next example, $name is private, so reaching for it directly from outside the class fails.
Private Example
Assigning a value to a private property from outside the class causes a fatal error:
Output: PHP script
<?php
class Fruit {
private $name;
public function get_details() {
echo "Name: " . $this->name . ".";
}
}
$apple = new Fruit();
$apple->name = "Apple"; // Error: Cannot access private property
$apple->get_details();
?>
Protected Access Modifier
protected sits in between: the class itself and its derived classes (child classes) have access, but outside code does not.
In the next example, $name is protected, so direct access from outside is not allowed.
Protected Example
Assigning a value to a protected property from outside the class causes a fatal error:
Output: PHP script
<?php
class Fruit {
protected $name;
public function get_details() {
echo "Name: " . $this->name . ".";
}
}
$apple = new Fruit();
$apple->name = "Apple"; // Error: Cannot access protected property
$apple->get_details();
?>
Protected with Inheritance
A child class is allowed to read a protected property it inherited:
Output: PHP script
<?php
class Fruit {
protected $name;
public function setType($name) {
$this->name = $name;
}
}
class Apple extends Fruit {
public function getType() {
echo "Name: " . $this->name . ".";
}
}
$apple = new Apple();
$apple->setType("Apple");
echo $apple->getType();
?>