1

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.

sadmansh
  • 917
  • 2
  • 9
  • 21

3 Answers3

1

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
}
Trent Three
  • 211
  • 2
  • 10
1

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;
?>
Malus Jan
  • 1,860
  • 2
  • 22
  • 26
0

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;
}
GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
  • @Sadman If my answer helped you, make sure you check that little check button next to my answer to mark it as correct. Please and thank you :) – GrumpyCrouton Jul 13 '17 at 19:52