What is Encapsulation in PHP?
In PHP, encapsulation is a fundamental concept in object-oriented programming (oops) that binds the data and methods within a class. It provides us protective barrier around the internal workings of an object.
In PHP, encapsulation means wrapping up data members and methods (functions) in a single module. In other words, it is a technique of binding data members and methods.
Hiding the essential internal property of that module is known as data abstraction.
When we wrap up data members and methods together into a single unit that is called Encapsulation.
It allows us to change class to internal implementation without affecting the overall functioning of the system.
Advantages of Encapsulation
- Data Hiding
- Code Organization and Maintainability
- Code Reusability
- Abstraction
- Security and Validation
- Flexibility and Extensibility
Disadvantages of Encapsulation
- Increased Complexity
- Overhead in Performance
- Dependency on Class Structure
- Limited Accessibility
- Potential for Code Duplication
- Testing Challenges
Example 1
<?php
class car{
public $name;
public $price;
function __construct($n, $p) {
$this->name=$n;
$this->price=$m;
}
public function setPrice($pr){
$this->pr=$pr;
}
public function display(){
echo "We have Kids Toy : ".$this->name."<br/>";
return $this->color=$this->pr;
}
}
// Create a Car object and set Car name, price
$obj=new car("THAR",5000000);
// Update the car price setPrice() method
$obj->setPrice(900000);
// Display the updated Price
echo "Price: ".$obj->display();
?>
Output
We have Kids Toy: THAR
Price : 900000
Example 2
<?php
class calculator{
var $x=100;
var $y=50;
function sum(){
$res=$this->x+$this->y;
echo "Addition (X+Y): ".$res."<br/>";
}
function sub(){
$res=$this->x-$this->y;
echo "Subtraction(X-Y): ".$res."<br/>";
}
function mult(){
$res=$this->x*$this->y;
echo "Multiplication (X*Y): ".$res."<br/>";
}
function div(){
$res=$this->x/$this->y;
echo "Division(x/y) : ".$res."<br/>";
}
}
$obj= new calculator( );
$obj->sum();
$obj->sub();
$obj->mult();
$obj->div();
?>
Output
Addition (X+Y): 150
Subtraction(X-Y): 50
Multiplication (X*Y): 5000
Division(x/y) : 2
Prev Next