0

Please help me find bug in my code. Why my function can't see varaibles, which is holded outside function?

    $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;
}

When I use pathTofile(); it returns "//". So it cant see variable outside.

  1. Why?
  2. How I can fix this?

EDIT: I'm using global $file; inside function, to tell function use global variables.

  • 2
    1. Read about the [scope of variables](http://php.net/manual/en/language.variables.scope.php) in PHP. 2. Pass the array as argument to the function. – axiac May 25 '17 at 13:44

2 Answers2

2

Method 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);

Method 2 using $GLOBALS if variable $file is global variable

$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);
Canh Nguyen
  • 333
  • 1
  • 18
0

You can do this :

function patToFile($sql,$action) use ($file){
    $path = $GLOBALS['file']['ip'] . "/" . $GLOBALS['file']['folder'] . "/" . $GLOBALS['file']['file'];
    return $path;
}
Yassine CHABLI
  • 3,459
  • 2
  • 23
  • 43