<?php
// Access modifiers in Php
// 1. Public - it can be accessed from anywhere
// 2. Private - it can only be accessed from within the class
// 3. Protected - it can be accessed from withing the class and from derived class
// By default the properties and methods are treated as public
// Private properties and methods can only be accessed by other member functions of the class
class Employee{
private $name = "opencodesolution";
function showName(){
echo "$this->name";
}
}
$opencodesolution= new Employee();
// echo $opencodesolution->name; -> This will not work if opencodesolution is private
$opencodesolution->showName();
?>
Hi Developer,
This article will learn about access modifiers in PHP.
In all of my previous articles, you have noticed that I have been writing public with the class properties. E.g. public $name= “opencodesolution”.
So what is public here? Before learn this, we have a class with the property $name
but this property provides us with an error, because we don't specified any access modifiers.
The main reason to get this error is as we know that we work with class and classes have their own sets of rules and variables inside a class that cannot be used by another function outside the class. So, to avoid this error we use access modifiers.
PHP oops there are three types of modifiers. public
, private
, and protected
. Now, one by one we will learn each of the concepts.
Public Access Specifier
Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.
Private Access Specifier
Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
Protected Access Specifier
Protected access specifier allows a child class to access the member variables and member functions of its base class.
If you try to access property with private
and protected
modifiers within the class
and within the class
and the classes derived from it you will be prompted with an error respectively.
Hope it can help you…
Categories : PHP