PHP Encapsulation In Hindi

📔 : PHP 🔗

data members को single Object में bind करना ही encapsulation कहलाता है। Encapsulation class में defined variables & methods को protect करने की protection mechanism होती है। encapsulation mechanism की help से हम data members पर अपनी need के according access restrictions define करते हैं , जिससे data को बाहर से access नहीं किया जा सके।


Encapsulation का simply मतलब होता है , End User से Program की implementation details को hide करना। Encapsulation के द्वारा ही data को External access से protect किया जाता है। जिसमे class properties को private define करते हैं और public methods के through उन properties को update / modify करते हैं।

File : php_encapsulation.php

Copy Fullscreen Close Fullscreen
<?php
        class Car
	{
		private $brand_name;
		private $color;
		private $price;

		/*define a public function to update info*/
		public function set_car_info($brand_name, $color, $price)
		{
			$this->brand_name = $brand_name;
			$this->color = $color;
			$this->price = $price;
			echo 'Car info set successfully !';
		}

		/* now define one more public function to show car info*/
		public function get_car_info()
		{
			echo 'Brand Name : '.$this->brand_name.'<br>'.
				'Color : '.$this->color.'<br>'.
				'Price : '.$this->price;
		}
	}
	$carObj = new Car();
	$carObj->set_car_info('TATA', 'Red', '700000');
	echo '<br>'; /*For line break*/
	$carObj->get_car_info();
        /*Now try with another data*/
	echo '<hr>'; /*For horizontal line */
	$carObj->set_car_info('FORD', 'Red Black', '1000000');
	echo '<br>';
	$carObj->get_car_info();
?>
Output
Car info set successfully !
Brand Name : TATA
Color : Red
Price : 700000

Car info set successfully !
Brand Name : FORD
Color : Red Black
Price : 1000000

PHP Advantages Of Encapsulation

  • Data Hiding And Abstraction

    Encapsulation use करके Unnecessary details, internal representation and implementation details को End user से hide किया जाता है , जिससे data structure को protect किया जा सके। किसी भी किसी class के members को private बनाकर इसके child class के access से रोका जा सकता है।

  • Reduces Code Complexity

    अब चूंकि class members को access modifiers का use करके एक single unit में bind करते हैं , जिससे code complexity भी reduce होती है।

  • Data Security

    Class properties/Methods को access modifiers का use करके need के according ही members का scope decide कर सकते हैं।

  • Code Reusability

    Code Reusability भी रहती है , same operation perform करने के लिए आपको code rewrite नहीं करना पड़ता है।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers