从另一个文件中的类访问文件中的变量


Accessing variables in a file from a class in other file

如果我有一个配置.php文件,里面有这样的变量......

配置.php

$cnf['dbhost'] = "0.0.0.0";
$cnf['dbuser'] = "mysqluser";
$cnf['dbpass'] = "mysqlpass";

然后,我如何从另一个文件中的类访问这些变量,例如...

Inc/dB.class.php

class db() {
  function connect() {
    mysql_connect($cnf['dbhost'], $cnf['dbuser'], $cnf['dbpass']);
  }
}
$db = new db();

因此,我可以在另一个文件中使用该类,例如...

索引.php

<html>
  <?php
    include('config.php');
    include('inc/db.class.php');
    $db->connect();
  ?>
</html>

在数据库脚本的开头包含包含、要求或require_once的配置文件。您还需要在要使用的函数中将$cnf指定为全局变量,否则无法访问全局变量:

include "../config.php";
class db() {
  function connect() {
      global $cnf;
      mysql_connect($cnf['dbhost'], $cnf['dbuser'], $cnf['dbpass']);
  }
}
$db = new db();

编辑:在大项目中,我更喜欢使用boot.php其中我包含所有php文件,所以我不需要在每个文件中包含我需要的所有内容。有了这个,我只需要将引导包含在索引中.php并且必须处置所有定义。它稍微慢一点,但真的很舒服。

只需将config.php包含在您的inc/db.class.php中即可。

编辑(回答评论中提出的查询)

你可以做的是有一个像下面这样的init.php

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

因此,您的类将能够从 config.php 访问变量。现在,对于您的index.php,您只需要包含init.php,并且将包含所有类,配置等。