1

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'; 
0

3 Answers 3

6

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

}
Sign up to request clarification or add additional context in comments.

1 Comment

Great, thank you! Just totally forgot that functions got their own local scope.
1

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

Comments

0

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.

Include.

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

1 Comment

Thank you for your idea - I already know this way but as I said it is an existent external application and I am unable to modify the file which terminates the ability to simply return an array in the config file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.