PHP Access Modifiers Example

Websolutionstuff | Sep-06-2021 | Categories : Laravel PHP

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

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="websolutionstuff";  
    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 :

websolutionstuff
websolutionstuff
websolutionstuff

 

 

Example 2 : Private

 

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

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

Output : 

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

 

 

Example 3 : Protected

 

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

Output : 

300
100

 


You might also like : 

Recommended Post
Featured Post
Laravel 10 CRUD Operation Step By Step
Laravel 10 CRUD Operation Step...

In this article, we will see how to create a crud operation in laravel 10. Here, we will learn about laravel 10 crud ope...

Read More

Feb-24-2023

Laravel tips: DB Models and Eloquent
Laravel tips: DB Models and El...

In the realm of web development, an efficient and robust data handling mechanism is paramount. Laravel, a PHP web applic...

Read More

Oct-11-2023

Laravel 9 Custom Helper Function Example
Laravel 9 Custom Helper Functi...

In this article, we will see laravel 9 custom helper function example. As we all know laravel provides many re...

Read More

Mar-07-2022

How To Create Pie Chart In Laravel 9 Using Highcharts
How To Create Pie Chart In Lar...

In this article, we will see how to create a pie chart in laravel 9 using highcharts. A pie chart is a circular statisti...

Read More

Oct-05-2022