PHP VariablesVariables are containers to store data. We can add or change or delete data from the variable and use them in our script. Here are some basic rules to create variables.Declaring variables in PHP
Variable should contain numbers, alphabet and underscore ( A-z, 0-9 AND _ )
After $ we can't use number it must be alphabet or underscore
Variables are case sensitive No need to declare variable type before using in PHP Type of Variables in PHP
gettype() to check the variable type.
PHP variables can take any type of data and change their type within the page also. ( in above example $my_var changes with type of data ) . It depends on its most recent assignment.
Scope of Variable
The variables declared as global are available throughout the script ( including inside the functions ). Variables declared inside functions is know as local variable ( to that function ) and are only available inside the function. So local variables declared inside a page are not available inside the functions of the page.
The associative array $GLOBALS holds the name of the variables as key and content as value of the variable. Once the variable is declared as element of $GLOBAL variable, then it is available throughout the script (including inside the functions).
More on Scope of variables in PHP functions Static variablesLocal variables get reset once the execution of function is over. We can retain the value and use them for subsequent function calls by declaring them as Static variable.
Output is here. See how static variable value is retained after execution of first call of the function whereas the local variable is destroyed.
Life of a variableAll variables are used within the page or within the script present in a page. As you are reading this page some variables are used to display the content of the page. These variables are lost as soon as this page execution is completed at server and downloaded to your browser. So how to pass the data or retain the data across the pages ? .
This article is written by plus2net.com team.
![]() |