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 defaultprotected
- the property or method can be accessed within the class and by classes derived from that classprivate
- the property or method can ONLY be accessed within the class
<?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
<?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()....
<?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 :
phpMyAdmin is a valuable web-based tool for managing MySQL databases, simplifying various database tasks. However, runni...
Jul-28-2023
In this article, we will see how to send email using markdown mailable laravel 9. we will learn laravel 9 to s...
Aug-05-2022
In this article, we will see laravel 9 one to many polymorphic relationship. A one-to-many polymorphic relation is...
Apr-05-2022
In this article, we will see an example of laravel 8 export buttons in datatables. If you want to export data...
Oct-14-2020