Difference between Public, Private and Protected in PHP
0 2836
To decide the scope of a variable or a function, in PHP we have mainly three access modifiers in PHP.
Access Modifiers:
Access modifiers are basically PHP Keywords which set the accessibility of the variables and methods. We can also set the accessibility of variables and functions of a class by setting the accessibility of class.
These are used in Inheritance to define the scope of instances of parent and child classes.
Syntax:1. Public:
This keyword used to make variables and functions accessible to anywhere means we can access either inside a class or anywhere outside the class.
Example:
<?php class Employees_details { public $employee_name; public $employee_id; } $obj = new Employees_details(); // creating the object of Employees_details class $obj->employee_name = 'Ramesh'; $obj->employee_id = '1221'; echo $obj->employee_name; echo '<br>'.$obj->employee_id; ?>
Output:
2. Protected:
This keyword used to make variables and functions accessible into that class and its child or derived classes.
Example:
<?php class Employees_details { protected $employee_name; } $obj = new Employees_details(); // creating the object of Employees_details class $obj->employee_name = 'Ramesh'; // it will give fatal error ?>
Output:
We can access protected properties by public functions of that class or by public functions of that child classes.
Example:
<?php class Employees_details { protected $employee_name; function get_employee($emp_name){ $this->employee_name=$emp_name; echo $this->employee_name; } } $obj = new Employees_details(); // creating the object of Employees_details class $obj->get_employee("Pooja"); ?>
Output:
3. Private:
This keyword used to make variables and functions accessible only into that class means we can't access private properties outside the class.
Example:
<?php class Employees_details { private $employee_name; } $obj = new Employees_details(); // creating the object of Employees_details class $obj->employee_name = 'Ramesh'; // it will give fatal error ?>
Output:
We can access protected properties by public functions of that class.
Example:
<?php class Employees_details { private $employee_name; } function get_employee($emp_name){ $this->employee_name=$emp_name; echo $this->employee_name; } } $obj = new Employees_details(); //creating the object of Employees_details class $obj->get_employee("Pooja"); ?>
Output:
Share:
Comments
Waiting for your comments