配置文件中的变量在类中不可用


variables in config file are not available in class

我有一个简单的问题,但似乎无法解决

$config['something'] = 'value';

这个文件包含在一个index.php中,在那里我还有一个__autoload函数。一切正常,配置文件在index.php中可用(我可以输出每个值),当我初始化一个类或调用一个静态对象时,自动加载器会完成这项工作。

问题是,我试图在加载的类中使用这些配置值作为参数,但我会得到每个类的"未定义变量:config"错误。我做错了什么?

config.php

$config['item1'] = 'value1';
$config['item2'] = 'value2';
$config['item3'] = 'value3';

index.php

require_once('config.php');
function __autoload()...

class.mysql.php

function connect() {
    mysqli_connect($connect['host'] etc.                            
...

显然,上面是我为说明文件之间的关系所做工作的简化版本。如何使config.php中的变量在自动加载的类中可用?

谢谢!

您面临的范围问题是,在函数外部创建的变量在函数内部不可访问,在函数内部创建的变量也在函数外部不可访问。

更多信息在这里:PHP变量Scpope

您有两种解决方案:

  1. 将$config数组作为参数传递到函数中

Index.php

require_once('config.php');
function __autoload($config)...

class.mysql.php

function connect($config) {
    mysqli_connect($connect['host'] etc.  

在行动中看到它:http://3v4l.org/RYfc0

  1. 使用全局

Index.php

require_once('config.php');
function __autoload()...

class.mysql.php

function connect() {
    //If you want to use the $config variable here
    global $config;
    mysqli_connect($connect['host'] etc.  

在行动中看到它:http://3v4l.org/ES4ej

就我个人而言,我更喜欢使用第一个解决方案,因为它可以帮助我更容易地理解$config变量来自