<?php
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
Always use visibility modifiers,not defaults.
Consider visibility when coding.
Make properties and methods public only when necessary.
Group properties and methods with similar visibility
File:class_visibility.php
<?php
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;
$student1->first_name='Dilip';
$student->last_name='Kumar';
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
//Note:
//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;
$student2->first_name='Sai';
$student2->last_name='Lakshmi';
echo $student2->hello_parent();