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.

1
  • 1
    You need to learn about variable scope. Commented Jul 13, 2017 at 19:47

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

The public keyword is only for use in a class structure.
Thank you so much!
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;
?>

Comments

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;
}

1 Comment

@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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.