Jaison Justus
Jaison Justus

Reputation: 2793

How to get array defined in a php file to a variable

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.

Upvotes: 3

Views: 5911

Answers (4)

Prasad Rajapaksha
Prasad Rajapaksha

Reputation: 6190

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;

Upvotes: 0

alex
alex

Reputation: 490153

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.

Upvotes: 6

Kambo_Rambo
Kambo_Rambo

Reputation: 1715

you might want to use 'require' ?

other than that, its perfectly acceptable.

Upvotes: 3

tamilsweet
tamilsweet

Reputation: 1007

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.
?>

Upvotes: 1

Related Questions