PHP OOP Object Iteration In Hindi

📔 : PHP 🔗

PHP में Object Iteration , Objects को define करने का एक way है , जिसमे हम किसी Objects के members (Variables) के बारे में जान सकते हैं। Object की foreach loop की help से Iterate किया जाता है।


By default , किसी class की सभी public properties को iteration के लिए use कर सकते हैं। क्योंकि public properties को class के बाहर से access किया जा सकता है।

PHP Object Iteration Example

File : php_object_iteration.php

Copy Fullscreen Close Fullscreen
<?php 
	class MyClass{

		private $priv_var = 'private variable';
		protected $prot_var = 'protected variable';
		public $pub_var = 'public variable';
	}

	$class = new MyClass();

	foreach($class as $key => $value) {
	    print "$key => $value";
	}
?>
Output
pub_var => public variable

Example में आप देख सकते हैं की सिर्फ public properties ही iterate हुई हैं।


अब अगर आप चाहते हैं कि protected और private properties भी iterate हों तो , class में एक public function बनाकर उसमे Object Iteration कर सकते हैं।
See Example -

File : php_object_iteration2.php

Copy Fullscreen Close Fullscreen
<?php 
	class MyClass{

		private $priv_var = 'private variable';
		protected $prot_var = 'protected variable';
		public $pub_var = 'public variable';

		/*define a function to iterate properties*/
		public function iterate_fun()
		{
			foreach($this as $key => $value) {
			    echo "$key => $value <br/>";
			}
		}
	}

	$class = new MyClass();
	$class->iterate_fun();
?>
Output
priv_var => private variable
prot_var => protected variable
pub_var => public variable

Note : किसी Object की आप सिर्फ non - static properties ही iterate कर सकते हैं क्योंकि non - static properties Object Scope में नहीं होती हैं उन्हें हम Class का Object बनाये बिना ही access कर सकते हैं।

Example में देखकर आप समझ सकते हैं कि किसी public function के through हम सभी properties को iterate कर सकते हैं , ऐसा इसलिए होता है क्योंकि class के अंदर तो हम सभी तरह की properties access कर सकते हैं।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers