I'd like to pass it's value as an argument into my function
function dostuff($input) {
global $input;
if ($input == 5) {
$output = "Success";
} else {
$output = "Failure";
}
echo $output;
}
Why does running
dostuff(5);
Not echo the output variable ("Success") like it's supposed to?
You don't need to set global $input;
, try this:
function dostuff($input) {
if ($input == 5) {
$output = "Success";
} else {
$output = "Failure";
}
echo $output;
}
With this, dostuff(5)
return "Success"
Explanation:
global
is to used global variable into your function (http://php.net/manual/en/language.variables.scope.php), you don't need it because you passed $input
in function parameters.
Expanding on Jouby’s explanation:
In PHP, unlike many other languages, variables are, by default, local variables. This simplifies some aspects of writing safe functions (with fewer accidental side-effects), but does require an extra step if you really want to use global variables.
In a function definition, parameter variables are really specialised local variables. The magic part of a parameter variable is that it is assigned automatically when yo call the function.
The global
keyword in PHP associates the variable name to the global variable, effectively replacing the local variable. You only need to use global
if you want to use global data, which is not generally a good idea.
In your example, that’s exactly what you have done. You have clobbered your local parameter with a non-existent global variable. Just remove that statement, and things should work.