0

I'm kind of slow in the head so can someone tell me why this isn't working:

function foo() {
 $bar = 'hello world';
 return $bar;
}
foo();
echo $bar;

I just want to return a value from a function and do something with it.

asked Feb 25, 2011 at 4:01
1
  • 1
    I don't know PHP, but have you tried echo foo();? Commented Feb 25, 2011 at 4:03

4 Answers 4

6

Because $bar does not exist outside of that function. Its scope is gone (function returned), so it is deallocated from memory.

You want echo foo();. This is because $bar is returned.

In your example, the $bar at the bottom lives in the same scope as foo(). $bar's value will be NULL (unless you have defined it above somewhere).

answered Feb 25, 2011 at 4:02
Sign up to request clarification or add additional context in comments.

Comments

4

Your foo() function is returning, but you're not doing anything with it. Try this:

function foo() {
 $bar = 'hello world';
 return $bar;
}
echo foo();
// OR....
$bar = foo();
echo $bar;
answered Feb 25, 2011 at 4:03

Comments

1

You aren't storing the value returned by the foo function Store the return value of the function in a variable

So

foo() should be replaced by

var $t = foo();
echo $t;
answered Feb 25, 2011 at 4:07

Comments

0

As the others have said, you must set a variable equal to foo() to do stuff with what foo() has returned.

i.e. $bar = foo();

You can do it the way you have it up there by having the variable passed by reference, like so:

function squareFoo(&$num) //The & before the variable name means it will be passed by reference, and is only done in the function declaration, rather than in the call.
{
 $num *= $num;
}
$bar = 2;
echo $bar; //2
squareFoo($bar);
echo $bar; //4
squareFoo($bar);
echo $bar; //16

Passing by reference causes the function to use the original variable rather than creating a copy of it, and anything you do to the variable in the function will be done to the original variable.

Or, with your original example:

function foo(&$bar) 
{
 $bar = 'hello world';
}
$bar = 2;
echo $bar; //2
foo($bar);
echo $bar; //hello world
answered Feb 25, 2011 at 4:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.