PHP Access Modifiers Example

In this article, we will see PHP access modifiers example. In PHP default access modifier is public. PHP provides different types of modifiers like private, public, or protected. Properties and methods can have access modifiers that control where they can be accessed.

So, let's see PHP access modifiers example, access specifier in PHP, default access modifier in PHP, access modifiers in oop, and PHP access modifiers.

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

 

Example 1: Public

 

<?php  
class parent  
{  
    public $name="techsolutionstuff";  
    function_display()  
    {  
        echo $this->name."<br/>";  
    }  
}  

class child extends parent
{  
    function show()  
    {  
        echo $this->name;  
    }  
}     

$obj= new child;  
echo $obj->name."<br/>";
$obj->function_display();
$obj->show();
?>

Output:

techsolutionstuff
techsolutionstuff
techsolutionstuff

 

 

Example 2: Private

 

<?php  
class Techsolutionstuff
{  
    private $name="techsolutionstuff";  
    private function show()  
    {  
        echo "This is private method of parent class";  
    }  
}

class child extends Techsolutionstuff  
{  
    function show1()  
    {  
    echo $this->name;  
    }  
}     
$obj= new child;  
$obj->show();  
$obj->show1();  
?>

Output : 

Fatal error:  Call to private method Techsolutionstuff::show()....

 

 

Example 3: Protected

 

<?php  
class Techsolutionstuff
{  
    protected $a=200;  
    protected $b=100;  
    function add()  
    {  
        echo $sum=$this->a+$this->b."<br/>";  
    }  
}     
class child extends Techsolutionstuff  
{  
    function sub()  
    {  
        echo $sub=$this->a-$this->b."<br/>";  
    }  
}     
$obj= new child;  
$obj->add();
$obj->sub();
?>

Output : 

300
100

 


You might also like : 

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS