是否可以在通过URL调用的函数内访问全局变量 - 如下所示:
网址
example.com/download.php?fn=download&fname=file
下面的第一个示例是否无效,因为函数调用直接转到download()
函数而不读取其余的PHP脚本? (即声明$var1, $var2
的地方)。
的download.php
<?php
$var1 = 'foo';
$var2 = 'bar';
global $current_user; // from elsewhere
if ($_GET['fn'] == "download")
if (!empty($_GET['fname']))
download($_GET['fname'], $current_user);
function download($fname, $current_user)
{
// Access the global variables in this scope
global $var1;
global $var2;
$output = $fname . $var1 . $var2;
echo $output // no output here...
}
但是这可以使用与上面相同的URL:
<?php
global $current_user; // from elsewhere
if ($_GET['fn'] == "download")
if (!empty($_GET['fname']))
download($_GET['fname'], $current_user);
function download($fname, $current_user)
{
// Access the global variables in this scope
$var1 = 'foo';
$var2 = 'bar';
$output = $fname . $var1 . $var2;
echo $output // "filefoobar"
}
有没有办法做到这一点,或者我只需要在函数中声明我的变量并跳过使用global
? (我知道global
通常是不明智的......等等。