简体   繁体   中英

PHP functions 101 question, really simple

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.

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).

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;

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;

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

ie $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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM