Open In App

PHP | Access Specifiers

In the PHP each and every property of a class in must have one of three visibility levels, known as public, private, and protected.
 

Generally speaking, it’s a good idea to avoid creating public properties wherever possible. Instead, it’s safer to create private properties, then to create methods that allow code outside the class to access those properties. This means that we can control exactly how our class’s properties are accessed. 
Note: If we attempt to access the property outside the class, PHP generates a fatal error.
PHP Access Specifier’s feasibility with Class, Sub Class and Outside World :
 



Class Member Access Specifier Access from own class Accessible from derived class Accessible by Object
Private Yes No No
Protected Yes Yes No
Public Yes Yes Yes

Below examples illustrate the Access Specifier of PHP: 
 




<?php 
class GeeksForGeeks
public $x = 100 ;  # public attributes
public $y = 50 ; 
    function add() 
echo $a = $this->x + $this->y ;
echo " ";
    }    
class child extends GeeksForGeeks
function sub() 
echo $s = $this->x - $this->y ; 
   
}   
 
$obj = new child; 
 
// It will return the addition result
$obj->add() ; 
 
// It's a derived class of the main class,
// which has a public object and therefore can be
// accessed, returning the subtracted result.
$obj->sub() ;
              
?> 

150 50




<?php 
class GeeksForGeeks
private $a = 75 ;  # private attributes
private $b = 5 ; 
    private function div()  # private member function
echo $d = $this->a / $this->b ;
echo " ";
    }    
class child extends GeeksForGeeks
function mul() 
echo $m = $this->a * $this->b ; 
   
}   
 
$obj= new child; 
 
// It's supposed to return the division result
// but since the data and function are private
// they can't be accessed by a derived class
// which will lead to fatal error .
$obj->div();
 
// It's a derived class of the main class,
// which's accessing the private data
// which again will lead to fatal error .
$obj->mul();
?> 

PHP Fatal error:  Uncaught Error: Call to private method 
GeeksForGeeks::div() from context '' in /home/cg/root/8030907/
main.php:22 Stack trace:#0 {main} thrown in /home/cg/root/8030907/
main.php on line 22




<?php
class GeeksForGeeks
{
protected $x = 1000 ; # protected attributes
protected $y = 100 ;
    function div()
{
echo $d = $this->x / $this->y ;
echo " ";
}
    }    
class child extends GeeksForGeeks
{
function sub()
{
echo $s = $this->x - $this->y ;
}
 
}
class derived # Outside Class
{
function mul()
{
echo $m = $this->x * $this->y ;
}
     
}
$obj= new child;
 
// It will return the division result
$obj->div();
 
// Since it's a derived class of the main class,
$obj->sub();
 
// Since it's an outside class, therefore it
// will produce a fatal error .
$obj->mul();
 
?>

10
900
Fatal error:  Uncaught Error: Call to undefined method 
child::mul() in /home/cg/root/8030907/main.php:32

 




Article Tags :