Rohit Goyani Rohit Goyani - 1 month ago 7
PHP Question

Why $GLOBAL is not working in function scope - PHP

I have write the code like same two times: on root of the file and in the function

$GLOBAL superglobal variable is not working in the function. But same thing already working in out of fuction

Reference:
1. php_superglobals
2. reserved.variables.globals

Code:

<?php

// working here
$GLOBALS['x'] = "Root of the file";
echo $x;

// same things are not working in the function.
function checkglobal() {
$GLOBALS['z'] = "In the function.";
echo $z;
}
checkglobal();


Output:


Root of the file

NOTICE Undefined variable: z on line number 10


Click and check here

Answer Source

I found my mistake in my code. $GLOBALS superglobal variable is used for creating global variable and access that in non-global scope. Need to declare the global variable with "global" keyword, if we want to use directly in non-global scope.

Corrected Code:

<?php

// working here
$GLOBALS['x'] = "Root of the file";
echo $x;

// same things are not working in the function.
function checkglobal() { 
    $GLOBALS['z'] = "In the function.";
    global z; // declare global variable *******************
    echo $z;
} 
checkglobal();

Output:

Root of the file

In the function.