PHP के Variables create करने से पहले उसके कुछ नियम समझे |
Rules for PHP Variables
- PHP का variable बनाने के लिए शुरुआत में $ (dollar) sign का इस्तेमाल किया जाता है |
- $ sign के बाद variable underscore(_) या किसी भी letter(A-Z, a-z) से start किया जाता है | For eg. $var, $_var
- किसी भी numeric value से variable की शुरुआत नहीं होती | For eg. $123var
- Variable alphanumeric भी होता है | For eg. $var123
- PHP Language ये Variable के बारे में एक case-sensitive language है | यहाँ पर $a और $A ये दोनों अलग-अलग variables है |
Variable Initialization
Source Code :Variable ये एक data को store करने का माध्यम है | program पर सभी प्रकार के data types को store किया गया है
Output for above Example
Source Code :Output :"; echo $b . "<br/>"; echo $c . "<br/>"; echo $d . "<br/>"; echo $e . "<br/>"; echo $f ; ?>
2 c 2.5 Hello 1
Variables Concatenation
PHP में एक variable को दुसरे variable के साथ जोड़ा जाता है |
Source Code :Output :
Hello WorldHelloFriends
Concatenation Variables with HTML Tags
Source Code :Output :"; echo "<strong>" . $var1 . $var2 . "</strong>"; ?>
Hello World Hello World
Variable Assigning Variable
यहाँ पर किसी variable की value किसी नए variable पर store की जा सकती है |
Source Code :Output :
Hello
Variable की value को बदला जा सकता है |
Source Code :Output :"; $var = "Hello Friends"; echo $var . "<br />"; ?>
Hello World Hello Friends
Variable Scopes
PHP के Variable को कहा पर declare किया जाता है | पर variables को access करने के लिए तीन scopes बनाये गए है |
- Local Variable
- Global Variable
- Static Variable
1. Local Variable
Local Variables सिर्फ function के अन्दर ही accessible होते है |
Source Code :Output :
Value of a : 10 Notice: Undefined variable: a in E:\xampp\htdocs\Variables.php on line 8 Value of a :
2. Global Variable
Global Variables; function के outside से access किये जाते है |
Source Code :Output :
Notice: Undefined variable: a in E:\xampp\htdocs\Variables.php on line 4 Value of a : Value of a : 10
Variable Using global Keyword
Global Variables function के outside से access किये जाते है | लेकिन वो function के लिए accessible नहीं होते |
जब global keyword के साथ variables; function के अन्दर लिखे जाते है तो वो variables function के लिए भी accessible रहते है |
Source Code :Output :"; echo "Value of b : $b <br />"; ?>
Value of a : 2 Value of b : 4
3. Static Variable
Without Static Variable
जब function में बिना static variable का इस्तेमाल किया जाता है तो,
जब func() call किया जाता है, तब उसमे जो variables होते है, वो एक बार ही initialized होते है | उसके बाद वो destroy हो जाते है |
Source Code :Output :"; $a++; } func(); func(); ?>
Value of a : 1 Value of a : 1
With Static Variable
जब function में static variable का इस्तेमाल किया जाता है तो,
जब func() call किया जाता है, तब उसमे जो variables होते है, वो अपनी values को hold करके रखते | ये variables destroyed नहीं होते |
Source Code :Output :"; $a++; } func(); func(); ?>
Value of a : 1 Value of a : 2