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
How to Add Toastr Notification in Laravel 11 Example
How to Add Toastr Notification...

Hello developer! In this guide, we'll see how to add toastr notification in laravel 11. Here, we'll di...

Read More

Apr-24-2024

How To Get Current Date And Time In Vue Js
How To Get Current Date And Ti...

In this article, we will see how to get the current date and time in vue js. In vue js very simple to get the current da...

Read More

Jan-14-2022

Multi-Stage Deployment Pipeline in Laravel 11 with GitHub Actions
Multi-Stage Deployment Pipelin...

In this guide, I'll walk you through setting up a multi-stage CI/CD deployment pipeline for your Laravel 11 project...

Read More

Oct-18-2024

How To Disable Dates After Week In jQuery Datepicker
How To Disable Dates After Wee...

In this tutorial, we will see how to disable dates after a week in jquery datepicker. In the date picker, we can di...

Read More

Jun-29-2022