3

I have a php file named config.php in which I defined the application settings in an array format like

<?php

return array(
 'user' => 'jaison',
 'email' => '[email protected]',
);

?>

Inside the main app files I need to get the array to a variable, so that they can be used like this.

<?php 
 $settings = include 'config.php';
?>

I would like to know if there is there any alternative method to do like this instead of using include.

4 Answers 4

6

Of course there are alternatives, but the way you are doing it is fine (this is how I'd do it) and I know at least of one popular framework that also does this.

The advantage of this method is you don't have to define any variables inside your include file (which would be imported into the namespace and may be clutter) and the returned structure and can be assigned to whatever is required.

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

Comments

3

you might want to use 'require' ?

other than that, its perfectly acceptable.

Comments

1

Not sure if there is another way without using include / include_once / require / require_once.

But you can use something like...

config.php

<?php
$settings = array(
 'user' => 'jaison',
 'email' => '[email protected]',
);

?>

In main app use

<?php 
 include 'config.php';
 // Use $settings as if its defined above.
?>

1 Comment

yes ur right. but the config.php file structure is strict like return array(....);. and not able to change the structure.
0

Since you use this setting inside all pages in your system. I think you can use constants.

Ex:

define("USER","jaison");
define("EMAIL","[email protected]");

So you can refer it anywhere once you included the config file.

Ex:

echo  USER;

1 Comment

The OP doesn't provide enough context, so constants are not necessarily the best way to go.

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.