oops in php

Modifiers in php

Mdifier Accessible Form
Public Anyware
Protected Inside this class and its subclasses
Private Inside this class only


class User{
private $is_admin=false;
private function has_admin_access(){
return $this->is_admin===true;
public function access_level(){
return $this->has_admin_access()?'Admin':'standard';
$user=new User;
echo $user->is_admin;//error:can not access private property
$user->is_admin=true;//error:can not access private property
echo $user->has_admin_access();//error:call to private method

echo $user->access_level();//'standard'

Best Practices

  1. Always use visibility modifiers,not defaults.
  2. Consider visibility when coding.
  3. Make properties and methods public only when necessary.
  4. Group properties and methods with similar visibility


class Student{
public $first_name;
public $last_name;
public $country='none';
protected $registration_id;
private $tuition=0.00;
public function full_name(){
return $this->first_name."".$this->last_name;
public function hello_world()
return 'Hello World';
protected function hello_family(){
return 'Hello family';
private function hello_me(){
return 'Hello me';

$student1=new Student;

echo $student1->full_name().'<br>';
echo $student1->hello_world().'<br>';

echo $student1->hello_family().'<br>';//get error
echo $student1->full_me.'<br>';//get error

echo $student1->registration_id;//get error
echo $student1->tuition;//get error

//To Access those functions we need to create another class,from that class
 //we can Access those functions

class PartTimeStudent extends Student{
public function hello_parent(){
return $this->hello_family();
$student2 =new PartTimeStudent;
echo $student2->hello_parent();


Dilip Kumar
Hello world
Sai Lakshmi
Hello family