Properties and methods can have access modifiers which control where they can be accessed. Access modifiers are essential for securing your objects and hiding internal logic that shouldn't be touched by the outside world (a concept known as Encapsulation).
There are three access modifiers in PHP:
public - The property or method can be accessed from anywhere. This is default if no modifier is set.protected - The property or method can be accessed within the class itself and by classes derived from that class (children).private - The property or method can ONLY be accessed within the class itself.
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
$mango = new Fruit();
$mango->name = 'Mango'; // OK
// $mango->color = 'Yellow'; // ERROR
// $mango->weight = '300'; // ERROR
?>
If you uncomment the $color or $weight lines in the example above, the PHP compiler will throw a Fatal Error.
If a property is private, how do you change its value? You use public methods inside the class to safely update the private data!
<?php
class BankAccount {
private $balance = 0; // Hidden from outside world
// Public method to safely interact with private property
public function deposit($amount) {
if($amount > 0) {
$this->balance += $amount;
}
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount();
$account->deposit(100); // Safe interaction
echo $account->getBalance();
?>