Home » PHP » What is the encapsulation in PHP?

What is the encapsulation in PHP?

Source

Wrapping some data in single unit is called Encapsulation. Encapsulation is used to safe data or information in an object from other it means encapsulation is mainly used for protection purpose.

class A {
	private $name;

	public function setName($name) {
		$this->name = $name;
	}

	public function getName($name) {
		return $this->name;
	}
}

$robin = new A();
$robin->setName('India');
$robin->getName();
                    

As per above class example field $name is encapsulated (private). Users of the class is not aware how $name is stored in A class. Right now the $name is stored in memory. We can modify internal code of class to store it to a flat file or event a database. Users of the class will not need to change any code, in fact they do not even know how $name is stored, because that is encapsulated and hided from them.

Check Also

What is the inheritance in PHP?

Inheritance is the process in which object of one class acquire the properties of another …

Leave a Reply

Your email address will not be published. Required fields are marked *