PHP Variable variables or $$ Variables

📔 : PHP 🔗

पिछले Topic में हमने पढ़ा कि Variables को कैसे define करते है , इस टॉपिक में हम जानेंगे कि $$variables क्या है।
$variable (single $) के साथ जब हम कोई variable define वो value उसे assign हो जाती है , यह Normal variable है , जबकि $$variable means हम किसी दूसरे variable की value को हम variable Define कर रहे हैं , या कह सकते हैं कि उस variable की value के नाम का variable define कर रहें हैं।

Example-

File : variables.php

Copy Fullscreen Close Fullscreen
<?php  
  $x = "Hello";
  $$x = "Rahul";
  echo $$x;
?>
Output
Rahul

जैसा कि आप देख सकते हैं , $$variable किस तरह से define किया।

चूंकि मैंने जैसा ऊपर कहा कि $$variable दूसरे variable की value के नाम का variable बनता है , तो अब अगर हम दूसरे variable में assign की गयी value के साथ access करें तो हमें same Output मिलेगा।

Example -

File : variables2.php

Copy Fullscreen Close Fullscreen
<?php  
  $x = "Hello";
  $$x = "Rahul";
  echo $Hello;
?>
Output
Rahul

तो अगर आप चाहे तो $$variable को दूसरे variable की value के साथ भी आसानी से access कर सकते हैं।

Access $$variable using {$variable}

$$variable को आप एक different तरीके से भी access कर सकते है , आप $$variable को ऐसा समझ सकते है की $ के बाद $variable की value replace हो रही है।

Example -

File : variables3.php

Copy Fullscreen Close Fullscreen
<?php  
  $x = "Hello";
  $$x = "Rahul Kumar";
  echo ${$x};
?>
Output
Rahul Kumar

Best Practice

हम जानते हैं कि जब हम Normal variable define करते हैं तो $ के बाद यदि white space आता है तो Error आती है बहीं अगर हम $$variable define करते समय $ के बाद अगर कोई white space या comment भी लिखते हो तो कोई error नहीं आएगी।

Example -

File : variables4.php

Copy Fullscreen Close Fullscreen
<?php  
    $foo = 'bar';
$

/*It will compile without notices or error as a variable variable.*/
$foo = 'Magic';
echo $bar; /* Outputs magic. */ ?>
Output
Magic

अब आप Clearly देख सकते है की मैंने single $ के बाद white space और comment भी लिखा हुआ है , और Program में कोई Error भी नहीं आयी। है।

Note - PHP हमें कुछ predefined variables भी provide करती है जिन्हे Super Global Variables कहते हैं।

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