简体   繁体   English

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

[英]Accessing variables in a file from a class in other file

If I have a config.php file with variables in it like so... 如果我有一个带有变量的config.php文件,就像这样...

config.php : 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 : 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 : index.php

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

Include config file with include , require or require_once at the beginning of your db script. db脚本开头的include配置文件包括includerequirerequire_once You will also need to specify $cnf as global in the function you want to use, otherwise you cannot access global variables: 您还需要在要使用的函数中将$cnf指定$cnf全局变量,否则无法访问全局变量:

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. 编辑 :在大型项目上,我更喜欢使用boot.php,其中包含所有php文件,因此,我不需要在每个文件中包含我需要的所有内容。 Having this, I just need to include the boot into the index.php and have to disposition all the definitions. 有了这个,我只需要将启动包含在index.php中,并必须处理所有定义。 It's slightly slower but really comfortable. 稍微慢一点,但是真的很舒服。

Just include config.php in your inc/db.class.php . 只需在您的inc/db.class.php包含config.php inc/db.class.php

EDIT (answering the query asked in comment) 编辑 (回答评论中询问的查询)

What you could do is have a init.php like the following, 您可以做的是像下面这样的init.php

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

So your classes will be able to access variables from config.php . 因此,您的类将能够从config.php访问变量。 And now for your index.php you only need to include init.php and all your classes, config, etc. will be included. 现在,对于index.php您只需包含init.php ,所有类,配置等都将包括在内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM