Possible Duplicate:
php function variable scope
I am using below code to test with a global variable. It seems that a global variable cannot be compared inside a function.
Why is it not displaying 'hello world' in the output?
Below is the code that I am trying:
<?php
$bool = 1;
function boo() {
if ($bool == 1) {
$bool = 2;
echo 'Hello World';
}
}
?>
When I remove function boo()
, 'hello world' is displayed. Why is it not displaying when function exists?
Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
A variable or function can be declared any number of times, but it can be defined only once. (Remember the basic principle that you can't have two locations of the same variable or function).
PHP The global Keyword The global keyword is used to access a global variable from within a function.
use global $var
to access your variable
<?php
$bool = 1;
function boo() {
global $bool;
if ($bool == 1) {
$bool = 2;
echo 'Hello World';
}
}
boo();
?>
Or a safer way using pointers would be to
function boo(&$bool) {
if ($bool == 1) {
$bool = 2;
echo 'Hello World';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With