为什么我还需要在index.php中声明require_once(' ../ config.php')?

时间:2012-10-01 04:24:47

标签: php include include-path

我的 database.php 里面已经有require_once('../config.php')。 我不明白为什么我仍然需要将require_once('../config.php')require_once('../database.php')放在我的 index.php 而不是require_once('../database.php')中,因为require_once('../config.php')是已经在 database.php 里面?

如果我删除 index.php 中的require_once('../config.php'),我收到错误。

<pre>Notice: Use of undefined constant DB_SERVER - assumed 'DB_SERVER' in C:\xampp\htdocs\lyndaphoto\includes\database.php on line 18

Notice: Use of undefined constant DB_USER - assumed 'DB_USER' in C:\xampp\htdocs\lyndaphoto\includes\database.php on line 18

Notice: Use of undefined constant DB_PASS - assumed 'DB_PASS' in C:\xampp\htdocs\lyndaphoto\includes\database.php on line 18

Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\lyndaphoto\includes\database.php on line 18

Warning: mysql_connect() [function.mysql-connect]: [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. (trying to connect via tcp://DB_SERVER:3306) in C:\xampp\htdocs\lyndaphoto\includes\database.php on line 18

Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\lyndaphoto\includes\database.php on line 18</pre>

config.php
$server = "localhost";
$user = "root";
$db_pass = "password";
$db_name = "photo_gallery";

define("DB_SERVER", $server);
define("DB_USER", $user);
define("DB_PASS", $db_pass);
define("DB_NAME", $db_name);


database.php

require_once("config.php");

class MySQLDatabase {


private $connection;    

function __construct() {
$this->open_connection();
}

public function open_connection() {
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if (!$this->connection) {
die("Database connection failed: " . mysql_error());
}else {
$db_select = mysql_select_db(DB_NAME, $this->connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
}
}

public function close_connection() {
if(isset($this->connection)) {
mysql_close($this->connection);
unset($this->connection);
}
}
}

$database = new MySQLDatabase();
$db =& $database;

这两个文件都在“localhost / photogallery / includes /”上 提前致谢! :)

2 个答案:

答案 0 :(得分:2)

代码中的所有内容均基于index.php(或正在运行的脚本),因此require_once("config.php")将在index.php的同一目录上搜索文件。请在database.php上尝试以下内容:

require_once(dirname(__FILE__) . "/config.php");

答案 1 :(得分:0)

处理包含文件的另一种方法是创建一个名为includes.php的文件。它将包含您的所有其他资源。

// Filename: includes.php

require_once 'database.php';
require_once 'config.php';

然后,在index.php和其他文档中,您可以通过包含该文件来访问所有应用程序的资源。

require_once 'includes.php';