请帮我查一下我的代码中的错误。 为什么我的功能无法看到可变的功能?
$file['folder'] = "/files/";
$file['file'] = "myFile.txt";
$file['ip'] = "http://127.0.0.1:1234";
function patToFile($sql,$action){
$path = $file['ip'] . "/" . $file['folder'] . "/" . $file['file'];
return $path;
}
当我使用pathTofile();
时,它会返回" //"。所以它看不到外面的变数。
修改
我在函数内部使用global $file;
来告诉函数使用全局变量。
答案 0 :(得分:2)
方法1
$file['folder'] = "/files/";
$file['file'] = "myFile.txt";
$file['ip'] = "http://127.0.0.1:1234";
function patToFile($sql,$action,$file){
$path = $file['ip'] . "/" . $file['folder'] . "/" . $file['file'];
return $path;
}
//Call function, Suppose already $sql, $action
pathToFile($sql, $action, $file);
如果变量$GLOBALS
是全局变量, 方法2 使用$file
$file['folder'] = "/files/";
$file['file'] = "myFile.txt";
$file['ip'] = "http://127.0.0.1:1234";
function patToFile($sql,$action){
$path = $GLOBALS['file']['ip'] . "/" . $GLOBALS['file']['folder'] . "/" . $GLOBALS['file']['file'];
return $path;
}
//Call function, Suppose already $sql, $action
pathToFile($sql, $action);
答案 1 :(得分:0)
你可以这样做:
function patToFile($sql,$action) use ($file){
$path = $GLOBALS['file']['ip'] . "/" . $GLOBALS['file']['folder'] . "/" . $GLOBALS['file']['file'];
return $path;
}