【发布时间】:2010-06-23 12:49:48
【问题描述】:
如何从函数中回显一个变量?这是一个示例代码。
功能测试() { $foo = 'foo'; //变量 } 测试(); //执行函数 回声 $foo; // 没有结果打印出来【问题讨论】:
-
你只是想打印变量吗?为什么不在函数内部打印呢?你想退货吗?还是您只是想在返回后打印它?
-
你不能打印一个没有在函数之前声明的变量。
标签: php
如何从函数中回显一个变量?这是一个示例代码。
功能测试() { $foo = 'foo'; //变量 } 测试(); //执行函数 回声 $foo; // 没有结果打印出来【问题讨论】:
标签: php
您的问题的直接答案是将$foo 导入函数的范围:
function test() {
global $foo;
$foo = 'foo'; //the variable
}
更多关于 PHP here 中的变量范围。
然而,在大多数情况下,这是不好的做法。您通常希望从函数中返回所需的值,并在调用函数时将其分配给$foo。
function test()
{
return "foo";
}
$foo = test();
echo $foo; // outputs "foo"
【讨论】:
变量生命范围就在函数内部。您需要将其声明为全局,以便能够在函数外部访问它。
你可以这样做:
function test() {
$foo = 'foo'; //the variable
echo $foo;
}
test(); //executing the function
或者按照建议将其声明为全局。为此,请查看此处的手册: http://php.net/manual/en/language.variables.scope.php
【讨论】:
function test() {
return 'foo'; //the variable
}
$foo = test(); //executing the function
echo $foo;
【讨论】:
您的$foo 变量在函数外部不可见,因为它只存在于函数的范围内。你可以通过多种方式做你想做的事:
来自函数本身的回显:
function test() {
$foo = 'foo';
echo $foo;
}
回显返回结果:
function test() {
$foo = 'foo'; //the variable
return $foo;
}
echo test(); //executing the function
使变量全局化
$foo = '';
function test() {
Global $foo;
$foo = 'foo'; //the variable
}
test(); //executing the function
echo $foo;
【讨论】:
我个人会这样做。
function test(&$foo)
{
$foo = 'bar';
}
test($foobar);
echo $foobar;
在函数参数部分使用与号告诉函数“全球化”输入变量,因此对该变量的任何更改都将直接更改函数范围之外的变量!
【讨论】: