PHP函数101问题,真的很简单

时间:2011-02-25 04:01:13

标签: php

我的头脑很慢,所以有人能告诉我为什么这不起作用:

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

foo();

echo $bar;

我只是想从函数中返回一个值并用它做一些事情。

4 个答案:

答案 0 :(得分:6)

因为在该函数之外不存在$bar。它的范围已经消失(函数返回),因此它从内存中释放出来。

你想要echo foo();。这是因为返回了$bar

在您的示例中,底部的$barfoo()的范围相同。 $bar的值为NULL(除非您已将其定义在某处)。

答案 1 :(得分:4)

你的foo()函数正在返回,但你没有做任何事情。试试这个:

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

echo foo();
// OR....
$bar = foo();
echo $bar;

答案 2 :(得分:1)

您没有存储foo函数返回的值 将函数的返回值存储在变量

所以

foo()应替换为

var $t = foo();
echo $t;

答案 3 :(得分:0)

正如其他人所说,你必须设置一个等于foo()的变量来处理foo()返回的内容。

即。 $bar = foo();

你可以通过引用传递变量来实现它的方式,如下所示:

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

通过引用传递会导致函数使用原始变量而不是创建它的副本,并且对函数中的变量所做的任何操作都将对原始变量进行。

或者,使用您的原始示例:

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

$bar = 2;
echo $bar; //2
foo($bar);
echo $bar; //hello world