PHP Encapsulation
Encapsulation is used to bind the data using get and set method or hide the values to prevent from unauthorized parties’ to directly access them. For encapsulation, we generally use the concept of visibility (public, private, protected).
Public Access
<?php
class Course{
public $subject;
public function getSubject()
{
return $this-> subject;
}
}
$student = new Course();
$student-> subject =”Php MySQL”;
echo $student-> getSubject();
?>
Output
Php MySQL
- When we declare the property or a method as public(encapsulated), it means this can be accessed anywhere outside the class; means can be modified from anywhere in your code.
- If we declare it private(encapsulated); it means this can’t be accessed anywhere in the class; means can be access only within code. If we run it shows the error
Fatal error: Uncaught Error: Cannot access private property Course: $subject
To overcome this, we use set method
<?php
class Course{
private $subject;
public function setSubject($s)
{
$this-> subject=$s;
}
public function getSubject()
{
return $this-> subject;
}
}
$student = new Course();
$student-> setSubject(“Php MySQL”);
echo $student-> getSubject();
?>