PHP ACCESS MODIFIERS

Samuel K.M - Oct 28 '21 - - Dev Community

Access Modifiers

Properties and methods can have access modifiers which control where they can be accessed.

There are three access modifiers:

public - the property or method can be accessed from everywhere. This is default
protected - the property or method can be accessed within the class and by classes derived from that class
private - the property or method can ONLY be accessed within the class

Check out the example below where we use the access modifiers on properties:

<?php
class Person{ 
 //properties of the class
 public $name;
 protected $age;
 private $gender;
}

$person = new Person();
$person->name = 'Samuel';//OK
echo $person->name;
$person1->age = 18;//Error
echo $person->age;
$person1->gender = 'Male';//Error
echo $person->gender;

Enter fullscreen mode Exit fullscreen mode

Check out the example below where we use the access modifiers on the methods:

<?php
class Person{ 
 //properties of the class
 public $name;
 public $age;
 public $gender;
 //methods of the class
 function setName($name){
   $this->name = $name;
 }
 protected function setAge($age){
   $this->age = $age;
 }
 private function setGender($gender){
   $this->gender = $gender;
 }
}
$person= new Person();
$person->setName('Samuel'); // OK
echo $person->name;
$person->setAge(18); // ERROR
echo $person->age;
$person->setGender('Male'); // ERROR
echo $person->gender;
?>

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .