Page 1 of 1
Using variables in a configuration file from another file
Posted: Thu Apr 02, 2009 12:25 pm
by jfeng
Hi,
I don't if this is possible, but I have a question about the following problem:
I want use the variables in a PHP application conf file like
<?
unset($CFG);
$CFG->dbtype = 'mysql';
$CFG->dbhost = 'localhost';
$CFG->dbname = 'dbname';
$CFG->dbuser = 'username';
$CFG->dbpass = '123456';
?>
Is it possible to pass the above settings to another PHP file so that I don't have to define the host name, user name and password over and over?
Thanks.
Jeffrey
Re: Using variables in a configuration file from another file
Posted: Thu Apr 02, 2009 12:33 pm
by Apollo
Save that file as "some/random/folder/config.php" and put this in another php file:
Code: Select all
require_once("some/random/folder/config.php");
It's now just as if the contents of config.php were in the other php.
Re: Using variables in a configuration file from another file
Posted: Thu Apr 02, 2009 12:46 pm
by jfeng
Apollo wrote:Save that file as "some/random/folder/config.php" and put this in another php file:
Code: Select all
require_once("some/random/folder/config.php");
It's now just as if the contents of config.php were in the other php.
Thanks. But I tried that and it didn't work. How do I refer to these variables? Do I use $CFG->dbname or $$dbname?
Thanks.
Jeffrey
Re: Using variables in a configuration file from another file
Posted: Thu Apr 02, 2009 1:20 pm
by Apollo
Refer to them just like you assign them, e.g. try this:
You're not exactly using the cleanest variable setup btw, since $CFG is not a defined class and you just access random members. I'm not even sure if that works with all PHP versions.
Instead I'd recommend:
Code: Select all
$CFG_dbname = 'dbname';
$CFG_dbuser = 'username';
etc
or
Code: Select all
$CFG = array();
$CFG['dbname'] = 'dbname';
$CFG['dbuser'] = 'username';
etc
Re: Using variables in a configuration file from another file
Posted: Thu Apr 02, 2009 1:55 pm
by php_east
here is another way...
Code: Select all
class mysql_config
{
var $dbtype = ""; //database type
var $dbhost = ""; //database host
var $dbname = ""; //database name
var $dbuser = ""; //database user
var $dbpass = ""; //database login password
function mysql_config()
{
$this->dbtype = 'mysql';
$this->dbhost = 'localhost';
$this->dbname = 'dbname';
$this->dbuser = 'username';
$this->dbpass = '123456';
}
}
and just do a
anywhere you need it.
and that's it.
Re: Using variables in a configuration file from another file
Posted: Thu Apr 02, 2009 1:57 pm
by php_east
Apollo wrote:I'm not even sure if that works with all PHP versions.
maybe not versions trouble, but it will fail when strict type checking is turned on, and there is a very good chance of that happenning, though usually it is not an issue.