Home >>PHP Object Oriented >PHP Encapsulation

PHP Encapsulation

Encapsulation in PHP

Encapsulation is a concept of wrapping up or binding up related data members and methods in a single module known as encapsulation And hiding the essential internal property of that module known as data abstraction.
<?php

class person

{

public $name;

public $age;

function __construct($n, $a)

 {

$this->name=$n;

$this->age=$a;

}

public function setAge($ag)

{

$this->ag=$ag;

}

public function display()

{

echo  "welcome ".$this->name."<br/>";

return $this->age-$this->ag;

}

}

$person=new person("Pankaj",25);

$person->setAge(20);

echo "You are ".$person->display()." years old";
 
?>
Output welcome Pankaj You are 5 years old

Create a arithmetic class with add( ),sub( ),mult( ) and div( ) method

<?php

class arithmetic

{

var $first=1000;

var $second=500;

function add()

{

$res=$this->first+$this->second;

echo "Addition = ".$res."<br/>";

}

function sub()

{

$res=$this->first-$this->second;

echo "Subtraction = ".$res."<br/>";

}

function mult()

{

$res=$this->first*$this->second;

echo "Multiplication = ".$res."<br/>";

}

function div()

{

$res=$this->first/$this->second;

echo "Division = ".$res."<br/>";

}

}

$obj= new arithmetic( );

$obj->add( );

$obj->sub( );

$obj->mult( );

$obj->div( );
 
?>
Output Addition = 1500 Subtraction = 500 Multiplication = 500000 Division = 2
In the above example Two properties $first and $second along with the methods add( ), sub( ), mult( ) and div( ) are defined in a single unit i.e in the class arithmetic. We create the object of class arithmetic. that object called the methods and methods are performed their task with defined properties. add( ) methods perform addition of two properties $first and $second. sub( ) methods perform subtraction of two properties $first and $second. mult( ) methods perform multiplication of two properties $first and $second. div( ) methods perform division of two properties $first and $second.

No Sidebar ads