In this tutorial, we will learn about Access Modifiers. Access Modifiers are used to control the accessibility of properties and methods. For example, you want to create a method that you do not want to make accessible from outside of the class. You can easily do this with the help of Access Modifiers.
Page Contents
Types of Access Modifiers:
There are three types of Access Modifiers in PHP, which are as follow.
- public
- protected
- private
Public:
This is the default access modifier in PHP. In case you do not write any access modifier with the method or property default access modifier will be there by default. Any property or method with a default access modifier can be accessed from everywhere.
<?php
class Example {
//variable with default access
public $var = "Python";
}
$obj = new Example();
echo $obj->var;
?>
Protected:
A method or property with protected access modifier can be accessed from with the class or in classes that are inheriting to that particular class. To apply a protected access modifier on your property or method you have to write a protected keyword along with an identifier. To understand the protected access modifier please check the following example program.
<?php
class Example {
//variable with protected access
protected $var = "Owlbuddy Programming Tutorials";
function show(){
echo $this->var;
}
}
$obj = new Example();
//will work Normally
$obj->show();
//will throw an Error (Please Uncomment following line to check)
//echo $obj->var;
?>
Private:
Any method or property with a private access modifier can be accessed only inside the class where it is defined. Please check out the following program to understand it.
<?php
class Example {
//variable with private access
private $var = "Owlbuddy Programming Tutorials";
function show(){
echo $this->var;
}
}
$obj = new Example();
//will work Normally
$obj->show();
//will throw an Error (Please Uncomment following line to check)
//echo $obj->var;
?>