$GLOBALS['value1'] is not working

My custom PHP script works on my PC over localhost. But, when I upload my code to the 'live' WordPress site, The $GLOBALS values are just null even they work on my localhost. (Nothing wrong with the database connection). Is the $GLOBALS not working on WordPress? My code is something like this one below:

$get_value = $db-query("SELECT * FROM mytable")-fetch();
$get_variable = $get_value['myvalue'];
function myfunction(){
   return $GLOBALS['get_variable']; 
}

Topic globals Wordpress

Category Web


The correct syntax for using with global keyword. To access a global variable in WordPress, you first need to globalize the variable with global $variable;

Write inside function.php as:

    function myfunction(){
       global $get_variable;
       $get_value = $db->query("SELECT * FROM mytable")->fetch();
       $get_variable = $get_value; 
    }

add_action( 'after_theme_setup', 'myfunction' );

Inside the function you can now able to any where. But, outside of this scope it needs to be re-declared as a global scope variable. Ex., to use inside single.php file, it will work as

global $get_variable;
echo $get_variable;

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.