doujie7886 2012-07-07 14:47
浏览 23
已采纳

从其他文件中的类访问文件中的变量

If I have a config.php file with variables in it like so...

config.php:

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

How can I then access these variables from a class which is in another file, such as...

inc/db.class.php:

class db() {

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

}
$db = new db();

So, I can use the class in another file such as...

index.php:

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

2条回答 默认 最新

  • duanhuanbo5225 2012-07-07 14:50
    关注

    Include config file with include, require or require_once at the beginning of your db script. You will also need to specify $cnf as global in the function you want to use, otherwise you cannot access global variables:

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

    EDIT: On big project I prefer to use a boot.php where I include all the php files, so I wont need to include in every file everything I need. Having this, I just need to include the boot into the index.php and have to disposition all the definitions. It's slightly slower but really comfortable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站