Php global variable across files
- how to create global variable in php
- how to set global variable in php
- how to declare global variable in php class
- how to declare global variable in php codeigniter
Global variable in php example!
PHP - Global Variables
In PHP, any variable that can be accessed from anywhere in a PHP script is called as a global variable.
Static variable in php
If the variable is declared outside all the functions or classes in the script, it becomes a global variable.
While global variables can be accessed directly outside a function, they aren’t automatically available inside a function.
Example
In the script below, $name is global for the function sayhello().
<?php $name = "Amar"; function sayhello() { echo "Hello " .$name; } sayhello(); ?>
However, the variable is not accessible inside the function. Hence, you will get an error message "Undefined variable $name".
Hello PHP Warning: Undefined variable $name in /home/cg/root/93427/main.php on line 5Example
To get access within a function, you need to use the "global" keyword before the variable.
<?php $name = "Amar"; function sayhello() { GLOBAL $name; echo "Hello " .$name; } sayhello(); ?>
It will produce the following output −
Hello AmarIf a function accesses a global variable and modifies it, the modified value
- how to create super global variable in php
- global variable in php with example