<?php
$foo = 1;
function meh(){
// <-- $foo can't be accessed
}
它看起来不像一个全局变量。但是,如果它在函数之外,它是否会像全局的东西那样有缺点?
最佳答案
在任何函数之外定义的所有变量都在全局范围内声明。如果你想访问一个全局变量,你有两个选择:
使用global关键字
<?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } ?>
或者使用$GLOBALS
<?php $a = 1; $b = 2; function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } ?>
阅读更多信息 http://php.net/manual/en/language.variables.scope.php
关于php - 函数外的变量是全局变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240600/