开发者

PHP Custom Global Variables

开发者 https://www.devze.com 2023-02-14 10:43 出处:网络
What\'s the best way to create variables that can be used from file to file and even object to object?Example:

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;
      }
   }
}
?>


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号