Php Encapsulation

What is Php Encapsulation?

Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
OR
Encapsulation means hiding the internal details of an object, i.e. how an object does something.
OR
Encapsulation is just when you want to hide stuffs into your object from the public
eg:- (i)capsule i.e. mixed of several medicines.
(ii) TV operation
It is encapsulated with cover and we can operate with remote and no need to open TV and change the channel.
Here everything is in private except remote so that anyone can access not to operate and change the things in TV.
Example:-


<?php
class company { 
public function get_fresherPackage() {
return 0; 
} 
public function display_fresherPackage() {
echo $this->get_fresherPackage();
}

}
class TCS extends company {
public function get_fresherPackage() {
return 'TCS provide 3.2 Lakh per annum';
}

}
class Oracle extends company {
public function get_fresherPackage() {
return 'Oracle provide 4.2 Lakh per annum';
}

}

$com_Obj = new company;
$com_Obj -> display_fresherPackage();

$tcs_Obj = new TCS;
$tcs_Obj -> display_fresherPackage();

$oracle_Obj = new Oracle;
$oracle_Obj ->display_fresherPackage();
?>

Output:- 0
TCS provide 3.2 Lakh per annum
Oracle provide 4.2 Lakh per annum

In the above example, we create an object of the class company, TCS, Oracle, and call the function display_fresherPackage() and it is showing the results.

TCS and Oracle class object is understandable but company class object is meaningless because which company showing the fresher package.

But if we want this method should not call by the company object then we create this method as a protected instead of public (So this is a part of Encapsulation because hide the function display_fresherPackage for class company object ).
Example:-


<?php
class company {
public function get_fresherPackage() {
return 0;
}
protected function display_fresherPackage() {
echo $this->get_fresherPackage();
}

}
class TCS extends company {
public function get_fresherPackage() {
return 'TCS provide 3.2 Lakh per annum';
}

}
class Oracle extends company {
public function get_fresherPackage() {
return 'Oracle provide 4.2 Lakh per annum';
}

}
$com_Obj = new company;
$com_Obj -> display_fresherPackage();

$tcs_Obj = new TCS;
$tcs_Obj -> display_fresherPackage();

$oracle_Obj = new Oracle;
$oracle_Obj -> display_fresherPackage();
?>
Call to protected method company::display_fresherPackage()