Clarkey
Clarkey

Reputation: 708

Accessing variables in a file from a class in other file

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>

Upvotes: 1

Views: 2126

Answers (2)

abhshkdz
abhshkdz

Reputation: 6365

Just include config.php in your inc/db.class.php.

EDIT (answering the query asked in comment)

What you could do is have a init.php like the following,

include('config.php');
include('db.class.php');
include('file.php');

So your classes will be able to access variables from config.php. And now for your index.php you only need to include init.php and all your classes, config, etc. will be included.

Upvotes: 2

Include config file with include, require or require_once at the beginning of your db script. You will also need to specify $cnf as global in the function you want to use, otherwise you cannot access global variables:

include "../config.php";

class db() {

  function connect() {
      global $cnf;
      mysql_connect($cnf['dbhost'], $cnf['dbuser'], $cnf['dbpass']);
  }

}
$db = new db();

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.

Upvotes: 3

Related Questions