Controlling Access with public, private and protected access modifiers.
These access specifiers can be used on both variables/attributes and methods.
In this video tutorial, we’ll demonstrate it using attributes.
Access Specifiers:
1. public
2. private
3. protected
Class With Attributes
< ?php
class container
{
var $a = 10;
public $b = 20;
private $c = 30;
protected $d = 40;
}
?>
var $a is similar to writing public $a
We shall extend class container to another class called contains.
Extending class is an inheritance property, and we shall discuss inheritance in another article. For now, know that, with extends keyword, all the properties and methods with public / protected access are inherited.
Extends
< ?php
class container
{
var $a = 10;
public $b = 20;
private $c = 30;
protected $d = 40;
}
class contains extends container
{
}
?>
Here, contents of class container is extended by class contains.
Object of class container
< ?php
class container
{
var $a = 10;
public $b = 20;
private $c = 30;
protected $d = 40;
}
class contains extends container
{
}
$obj1 = new container();
echo $obj1->a;
echo $obj1->b;
?>
This outputs: 10 and 20 respectively.
Object of class contains
< ?php
class container
{
var $a = 10;
public $b = 20;
private $c = 30;
protected $d = 40;
}
class contains extends container
{
}
$obj2 = new contains();
echo $obj2->a;
echo $obj2->b;
?>
This outputs: 10 and 20 respectively.
i.e., public attributes are inherited
Accessing private / protected attributes outside class
< ?php
class container
{
var $a = 10;
public $b = 20;
private $c = 30;
protected $d = 40;
}
class contains extends container
{
}
$obj1 = new container();
echo $obj1->c;
echo $obj1->d;
?>
It through’s error, since you cannot access, private and protected variables/attributes outside the class.
Now lets check if private and protected variables are actually inherited:
Inheriting private attribute
< ?php
class container
{
var $a = 10;
public $b = 20;
private $c = 30;
protected $d = 40;
}
class contains extends container
{
function __construct()
{
echo $this->c;
}
}
$obj1 = new contains();
?>
This through’s error, because $c is not inherited to class contains and thus not present inside class contains. Which means, private variables and methods cannot be inherited.
Inheriting protected attribute
< ?php
class container
{
var $a = 10;
public $b = 20;
private $c = 30;
protected $d = 40;
}
class contains extends container
{
function __construct()
{
echo $this->d;
}
}
$obj1 = new contains();
?>
Output’s 40.
This means, protected variables and methods are inherited.
Access Specifiers: PHP OOP
Conclusion
public attributes and methods are inherited and can be accessed outside the class.
private attributes and methods cannot be inherited and cannot be accessed outside the class.
protected attributes and methods can be inherited but cannot be accessed outside the class.