0

What's the best way to create variables that can be used from file to file and even object to object? Example:

The settings file would contain an array like this:

<?php
$config = array(
            'key1' => 'val1',
            'key2' => 'val2'
);
?>


<?php
class config {
   function get_data($file){
      require_once('config/'.$file.'.php');
      foreach($config as $key => $val){
           $this->$key = $val;
      }
   }
}
?>
2
  • It really depends on the usage of the variable. You could use sessions / cookies / db storage, etc. Please elaborate or the usage of the variable. Commented Mar 2, 2011 at 4:15
  • possible duplicate of Reading and Writing Configuration Files Commented Mar 2, 2011 at 8:07

2 Answers 2

5

The best way would be to use define() in your PHP config file and include that across the site. This will protect you from accidentally overwriting the value in your config.

However, the problem with this is, arrays are not allowed. Only scalar and null values are allowed.

An alternative to this would be use a config file in conjunction with a static class. Only the static class should directly access the file and you can use the class to get values.

CakePHP and Zend (among others) use this method

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

2 Comments

among many, many, many others. config file + static class is a good and widespread solution.
@ithcy statics are widespread but definitely not "good": misko.hevery.com/code-reviewers-guide/…
0

Just define some array / variables in config.php and include it in all your phps if all you need are global site configuration properties (such as username and password to database, path to save uploaded files in, and the likes).

Comments

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.