PHP Variables are represented by a dollar sign($). Variables store the information, it's like container means store something
As per below example, $website is variable name and it is hold "qoify.com"
$website = "qoify.com";
$GLOBALS | $_SERVER | $_GET | $_POST | $_FILES |
$_REQUEST | $_SESSION | $_COOKIE | $_ENV | $php_errormsg |
$HTTP_RAW_POST_DATA | $http_response_header | $argc | $argv |
When a variable is declared within funaction, then variable scope is local.
function local_scope() { $a=5 ; /* local scope variable */ } local_scope(); echo $a; //Output :: Notice: Undefined variable: a
The above example will not any value of $a because $a has local scope in function
include 'test.php'; echo $a; //Output :: 5
I above example, we have created one file "test.php" and declare a variable "$a", and it's include in another file. $a variable will be available
When the variable is declared outside of a function and access global variable inside function, use the global keyword.
$a=4; function global_scope_test() { global $a;// global access $a = $a+5; } global_scope_test(); echo $a; //Output :: 9
$a=4; function global_scope_test() { $GLOBALS['a'] = $GLOBALS['a'] + 5; } global_scope_test(); echo $a; //Output :: 9
$GLOBALS | $_SERVER | $_GET | $_POST | $_FILES |
$_REQUEST | $_SESSION | $_COOKIE | $_ENV |
$a=4; function superglobals_test() { echo $_SESSION['name']; // This is superglobals variable, we can get the value of name variable echo $_POST['age']; // This is superglobals variable, we can get the value of age variable }
PHP static variable used for the local variable not to be deleted after program execution is done, A static variable exist in local variable scope, use the static keyword.
//without static keyword function test() { $a=5; echo $a; $a++; } test(); // 5 test(); //5 //with static keyword function static_test() { static $a=5; echo $a; $a++; } static_test(); //5 static_test(); //6
function static_test() { static $a=5; // correct static $b = 5*4; // correct static $name = trim(' ABC'); // Incorrect beacause trim is function echo $a; $a++; }
Static declarations are resolved in compile-time.
Reference variables are not stored statically.
$message = 'Hello'; $$message = 'World'; echo $Hello; // World echo "$message $Hello"; // "Hello World" echo "$message ${$message}"; // "Hello World"
Reference : PHP