If I have a config.php file with variables in it like so…
config.php:
$cnf['dbhost'] = "0.0.0.0";
$cnf['dbuser'] = "mysqluser";
$cnf['dbpass'] = "mysqlpass";
How can I then access these variables from a class which is in another file, such as…
inc/db.class.php:
class db() {
function connect() {
mysql_connect($cnf['dbhost'], $cnf['dbuser'], $cnf['dbpass']);
}
}
$db = new db();
So, I can use the class in another file such as…
index.php:
<html>
<?php
include('config.php');
include('inc/db.class.php');
$db->connect();
?>
</html>
Include config file with include, require or require_once at the beginning of your db script. You will also need to specify
$cnfas global in the function you want to use, otherwise you cannot access global variables:EDIT:
On big project I prefer to use a boot.php where I include all the php files, so I wont need to include in every file everything I need. Having this, I just need to include the boot into the index.php and have to disposition all the definitions. It’s slightly slower but really comfortable.