0

How do I defined a global variable that I can use across blocks of code?

In my case, I need to declare my global var within an included header.php and then I need to be able to use it within another included file.

Ultimately, I'd like to be able to access it anywhere since it changes. And it's not sensitive information... just a number.

1 Answer 1

2

Just use the global keyword to modify the variable's score. It doesn't matter if you reference the variable in a file that is included, you just need to use the global keyword.

In header.php:

$var = 'Something';

In included_file.php:

function a()
{
    global $var;
    echo $var;
}

echo $var; // Will print 'something'

a(); // Prints 'Something'

Alternatively, you can use the $GLOBALS array.

Finally, if it's static and not going to change, you can define constants:

define('MY_NUMBER', 10);

echo MY_NUMBER; // Outputs 10
Sign up to request clarification or add additional context in comments.

Comments

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.