0

它的代码非常简单,但我不明白这是什么意思:(

function aaa($b){
$a = 30;
global $a,$c;
return $c=($b+$a);}
echo aaa(40); //Output is 40

为什么输出是 40 ?当我在函数之外调用 $a 时,它给了我想要的答案,那有什么意义呢?

$a = 30;
function aaa($b){
global $a,$c;
return $c=($b+$a);
}
echo aaa(40); //Output is 70


function aaa($b){
global $a,$c;
$a = 30;
return $c=($b+$a);
}
echo aaa(40); //Output is 70
4

4 回答 4

1

See what the global keyword stands for here:

function aaa($b) {
    $a = 30;               # local variable, will be overwritten just in the next line
    global $a, $c;         # importing $a from the global scope - NULL
    return $c = ($b + $a); # $c = (40 + NULL)
}

The manual at http://php.net/global reminds that a global variable influences the function if it is used inside there. That is not only for the first call but also for all subsequent calls.

This makes the function non-deterministic, so less useful code and you might - as you just did - get irritated by it.

An easy way out is: Instead of putting parametric values of that function into global variables, turn them into parameters:

function aaa($a, $b, &$c) {
    return $c = ($b + $a);
}

echo aaa(30, 40, $c); //Output is 70

The code is not only much easier to read but also deterministic. It will always behave the same when called. That means less guessing.

This example still has the problem of returning a value by a parameter (by reference), however you might see as well that this is not really necessary any longer:

function aaa($a, $b) {
    return ($b + $a);
}

echo $c = aaa(30, 40); //Output is 70

Lessons to take away:

  • Do not use global variables inside functions - they only stand in your way.
  • Reduce the number of parameters a function has (that are about all incomming values, so global counts as well).
于 2013-04-20T07:45:36.667 回答
1

当使用 exampleglobal $a;时,PHP 会覆盖该变量$a并为其分配一个引用,就好像该语句被替换为:

$a = &$GLOBALS["a"]; // and the same with every other variable which is used in global

正如$a您的第一个示例中未定义的那样,$GLOBALS["a"]评估为null,因此$a成为对持有null值的变量的引用。

尝试var_dump($GLOBALS);在函数调用之后和之前。它将向您显示一个以a函数调用命名的新索引(带有值null或您分配给它的值)。

(Ps:实际上它是对主范围内的变量进行直接引用。)

于 2013-04-20T09:52:13.123 回答
0
in php a variable Scope priority is 
 1- local variable
 2- global variable

even you determine global $a in function body but local variable $a used when it apear. refer to Php variable reference if you want use global variable with same name of your local variable you must user $GLOBALS['c']=$GLOBALS['a']+$b; if $c and $a is global definition hope this help

于 2013-04-20T07:48:37.257 回答
0

我认为,在第一种情况下 $a 是未定义的。首先写入 $a 的值,然后调用函数。使用页面顶部的 error_reporting(E_ALL) 来了解脚本中的错误。

于 2013-04-20T07:57:26.293 回答