PHP Variable rules:
- The variable starts with the $ sign, followed by the name of the variable
- Variable names must begin with a letter or underscore
- Variable names cannot start with a number
- Variable names can contain only alphanumeric characters and underscores (A-Z, 0-9, and _)
- Variable names are case sensitive ($y and $Y are two different variables)
Note: The PHP variable name is case-sensitive!
Local and Global Scopes
Variables declared outside the function have Global scope and can only be accessed outside of the function.
Variables declared inside a function have a local scope and can only be accessed inside the function.
1<?PHP2 $x= 5;//Global Scope3 4 functionmyTest () {5 $y= 10;//Local Scope6 Echo"Variable:</p> inside the <p> test function";7 EchoThe variable x is:$x";8 Echo"<br>";9 EchoThe variable y is:$y";Ten } One A myTest (); - - Echo"Variable:</p> outside of the <p> test function"; the EchoThe variable x is:$x"; - Echo"<br>"; - EchoThe variable y is:$y"; -?>PHP Global Keywords
The global keyword is used to access variables within the function.
To do this, use the Global keyword before (inside the function) variable:
1<?PHP2 $x=5;3 $y=10;4 5 functionmyTest () {6 Global $x,$y;7 $y=$x+$y;8 }9 Ten myTest (); One Echo $y;//Output A?>
PHP also stores all global variables in an array named $GLOBALS [index]. The subscript contains the variable name. This array is also accessible within the function and can be used to update global variables directly.
The above example can be rewritten like this:
1<?PHP2 $x=5;3 $y=10;4 5 functionmyTest () {6 $GLOBALS[' Y ']=$GLOBALS[' X ']+$GLOBALS[' Y '];7 } 8 9 myTest ();Ten Echo $y;//Output One?>PHP Static Keywords
Typically, all variables are deleted when the function finishes/executes. However, sometimes I need to not delete a local variable. Achieving this requires a bit of further work.
To do this, use the static keyword when you first declare a variable:
1<?PHP2 3 functionmyTest () {4 Static $x=0;5 Echo $x;6 $x++;7 }8 9 myTest ();Ten myTest (); One myTest (); A -?>
Php--01