I need to require/ include a file to fetch configuration values from a foreign software into the one I am just developing.
Is it possible to somehow process the external php file via include/ require and either load all variables from it into an array or at least set it into kind of a custom namespace to prevent it from resetting existent variables?
The external application is pretty old and uses plain PHP and variable assignments to prepare it for the run.
Example:
$db_type = 'mysql';
$db_user = 'hello';
$db_pass = 'world';
$charset = 'UTF-8';
You can include this code inside of a function. And all these variables will be in the local scope.
function get_old_data() {
include 'old.php';
// do whatever you want with these variables
}
You can use return inside included file.
It is possible to execute a return statement inside an included file in order to terminate processing in that file and return to the script which called it.
Example:
// config.php
return array('db_type' => 'mysql',
'db_user' => 'hello',
'db_pass' => 'world',
'charset' => 'UTF-8',);
Then use it like this
$config = include 'config.php';
Even like this
$connection = new Connection(include 'config.php');
I'm assuming you know the names of the config vars you want to use from the external config.
You could create a function in which you include the file, build an array from the vars, and that you can then return to the caller.
In that case the external file will be executed in the function's local scope, and should not override outer vars.
function loadconfig() {
include 'external.php';
// do calculations and build var_array
return $var_array;
}