dqybjj3497 2014-06-13 16:51
浏览 23

通过项目传递数组

Everybody has it, an array or object that needs accessing throughout your entire project. This can be settings, an array of user data or anything else that does not qualify for for a defined variable (cause defined array's are bad m'kay).

I'm probably not looking for the right type of thing, but I need a way to access an object in every class, function or page.

So for example sake, lets say I have a standard config file with this:

<?php
return array(
    'database' => array(
        'driver' => 'mysql',
        'mysql' => array(
           'host' => 'localhost',
           ...
        ),
        'mongodb' => array(
            'host' => 'localhost',
            ...
        ),
        ...
    ),
);
?>

I get it by doing:

$config = (require('path/file.php'));

So, now I have my config. But this doesn't pass around. I don't want to call "$config = (require('path/file.php'));" everytime I need a setting.

So is there a way to always call this only once by, for example, storing it in a class or something (without having to define that class all the time obviously, cause that defeats the point).

Now I know about globals. But I'm not really partial to them for several reasons. Mysql is not an option cause it's a config file and users need to be able to alter it before launch.

  • 写回答

3条回答 默认 最新

  • drbd65446 2014-06-13 17:02
    关注

    Not tested

    In Config.php

    class Config
    {
        public static function get()
        {
            return array(
                'database' => array(
                    'driver' => 'mysql',
                    'mysql' => array(
                        'host' => 'localhost',
                        ...
                    ),
                    'mongodb' => array(
                        'host' => 'localhost',
                        ...
                    ),
                    ...        
                ),
            );
        }
    }
    

    In your index.php:

    function __autoload($classname) {
        $filename = "./". $classname .".php";
        include_once($filename);
    }
    

    In the file you want your conf:

    $myConf = Config::get();
    

    You can also improve the class to easily get a particular config data

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100