Reputation: 43
I have a little function that has a string parameter. Now I want a variable defined within that function to be known outside of that function where the function is being executed.
function somefunc($hello) {
$hello = "hi";
$bye = "bye";
return $bye;
}
And using that function in another php script.
somefunc("hi");
echo $bye;
The other script in which the function is being used and in which I'm trying to echo out the variable keeps telling me that the variable bye has not been defined. How can I get its value without making it global? The other script has the function included in it properly, so this cant be the problem.
Thanks in advance for any help!!
Upvotes: 0
Views: 699
Reputation: 2984
Your syntax is the problem. To fix the current issue you need to first define a variable with the return variable or echo it.
function somefunc($hello) {
$hello = "hi";
$bye = "bye"
return $bye;
}
echo somefunc("hi"); // bye
// --- or ---
$bye = somefunc("hi");
echo $bye; // bye
The variable defined within that function cannot be accessed outside of its context (the function).
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.
For a better understanding of variable scopes check out the docs in the PHP manual; they are pretty good at breaking it down.
You could also look at global references of variable in the PHP manual and it may work for what you are trying to do.
Upvotes: 1