简体   繁体   中英

How to use variables from php file where require/include is declared

So basically, I have a config.php file for connecting to the mysql database, and a functions.php file that includes some functions. In all my files (eg. index, login, register), I use the line require('config.php'); and inside config.php I have this line require('functions.php'); for including the config + functions together using the line require('config.php'); in my index, login, and register.php files.

So basically my problem is, the variables that I've declared in config.php are not recognized inside functions.php. How do I make it work?

Thanks in advance.

Use the global statement to declare variables inside functions as global variables.

function myfunction() {
  global $myvar;  // $myvar set elsewhere can be read within this function
                  // and if its value changes in this function, it changes globally
}

You can use global variavlename or $GLOBAL['variavlename without $']

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a;
    $a = $a + $GLOBALS['b'];
} 

Sum();
echo $a;
?>

It's very likely your functions don't work because their scope does not include the variables you are trying to use .

First, make sure functions.php is being included after the variables are set

Also, make your functions Public Functions , OR, declare global variables inside functions by doing this:

$testVariable = "test";
function testFunction() {
     global $testVariable;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM