0

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!!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, that worked. But now my problem is that I have a if statement in there and when it gets triggered, the value of the variable is being changed. Now, although the if condition has been triggered, the value of the returned variable is still the same as before the if condition has been triggered. Is there any way how to have a function return a variable that is being manipulated within that function and depending on what condition has been triggered, has a different value?
@DNYX could you share the code? This would be helpful in debugging what you are describing as there is no clear reason.
EDIT: Sorted itself out. Found the problem. Thank you anyways :)

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.