You are asking about defining a local variable, but that by itself would not solve your problem.
For the sake of those getting here by a search, I'll answer both.
- How to define a local variable in a function:
PHP defines a variable on its first use. There is no keyword for declaring a local scope. All variables inside functions are local by default (even a variable with the same name as another global variable).
'A first use' means assigning a value, not using the variable in return or a condition. If you are not certain that the variable you use on return will be assigned a value (e.g. inside a config.php file), then you need to initialize it using a value of desired type. e.g.: $user = ''.
- import an external config.php file inside a local scope of a function
You wanted to:
Define a local variable inside a function, accessible only inside that function's scope. This local variable $user is assigned a value from the config.php file.
$user must not be visible from outside of that function.
You need to put the require_once statement inside that function.
If the include occurs inside a function within the calling file, then
all of the code contained in the called file will behave as though it
had been defined inside that function.
http://php.net/manual/en/function.include.php
function ha(){
static $user;
require_once('../config.php');
if (!isset($user)) { $user = ''; } // Only needed if you are not sure config.php will define the $user variable
return $user;
}
echo ha();
echo $user; // Will output nothing
Using static keyword will let the function keep the value of $user. This is needed, because if you call the function a second time, file config.php will not be included again (require_once()).
PHP has three variable scopes, global, local, and static. Static is not the same as local, but it behaves the same in a sense to where the variable is accessible. Static scope in a function is a PHP specialty, read about it.
when I define $user in function static I get an empty value..
You do, because when you used require_once() outside of the function, $user variable was defined in global scope. Then you defined another $user variable inside the ha function by using $user, without declaring it to be global by global $user, as you did later.