为什么我的函数无法看到此数组字符串

时间:2017-05-25 13:42:20

标签: php

请帮我查一下我的代码中的错误。 为什么我的功能无法看到可变的功能?

    $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();时,它会返回" //"。所以它看不到外面的变数。

  1. 为什么?
  2. 我如何解决这个问题?
  3. 修改 我在函数内部使用global $file;来告诉函数使用全局变量。

2 个答案:

答案 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;
}