PHP Encapsulation

« Previous Tutorial Next Tutorial »

Encapsulation in PHP refers to a concept where we encapsulates all the data and member functions together to form an object.

In other words, you can say that encapsulation in PHP is basically wrapping up of data member and method together into a single unit, that is, class.

Why Encapsulation ?

Encapsulation is to hide internal details of an object in a PHP program.

You can use encapsulation to prevent your client to see its inside view.

PHP Encapsulation Example

Here is an example demonstrating encapsulation in PHP.

<!DOCTYPE html>
	<title>Encapsulation Example in PHP</title>
	class WhoAreYou
		public $firstname;
		public $lastname;
		function __construct($fname, $lname)
			$this->firstname = $fname;
			$this->lastname = $lname;
		public function what_i_like()
			echo "I just like to read everything on ".$this->firstname.$this->lastname;
	$object_of_WhoAreYou = new WhoAreYou("Codes", "Cracker");
	echo $object_of_WhoAreYou->what_i_like();

Here is the sample output produced by the above encapsulation example code in PHP.

php encapsulation

« Previous Tutorial Next Tutorial »


Quick Links
Signup - Login - Give Online Test