How to make variables visible when including some file. For example:
code.php:
<?php
global $var; $var = "green";
?>
index.php:
<?php
include("code.php");
Function index(){
echo "The apple is $var";
}
?>
Please note that in code.php there are a lot of global variables (~150 variables) and all variables are used in many different functions inside the index.php.
This is an issue to do with variable scope, plus you do not need to be defining $var
as a global.
When you include a file, you can imagine in your head that it is just copy-pasting the contents of the other file into the current file.
E.g.
code.php
$includedName = 'Tom';
index.php
include 'code.php';
function sayHello($name)
{
echo 'Hello ' . $name;
}
sayHello($includedName); // Hello Tom
You've mentioned you are working with legacy code, so it may be worthwhile to preserve the use of globals for the sake of consistency - though using globals is generally considered to be very bad practice, I'd generally consider inconsistently using globals to be worse.
To break function scope and pull in variables from the global scope you must invoke the global
keyword from within the function:
<?php
$var = "green";
Function index(){
global $var;
echo "The apple is $var";
}
?>
This answer sums up why global
variables are considered to be bad practice:
There's no indication that this function has any side effects, yet it does. This very easily becomes a tangled mess as some functions keep modifying and requiring some global state. You want functions to be stateless, acting only on their inputs and returning defined output, however many times you call them.
However, in this specific example, you are not modifying $var
's state - only reading it. So the issues are minimal.
The problems with global state can be read about in more depth on Programmers.SE.