2013-03-10 100 views
1

我想做一个PHP网站,但我有一个问题,我不能在包含的文件中使用包含的变量!PHP - 未声明的变量后要求

的index.php

<?php 
require 'core/init.php'; 
?> 

的init.php

<?php 
require 'config.php'; 

require 'db/connect.php'; 
?> 

的config.php

<?php 
// Config 
// The Title of the site 
$site_title = 'php-site'; 
$site_desc = 'A awesome PHP site!'; 
$site_keywords = 'php, html5, css3, awesome'; 
$site_author = 'erty5000'; 

// Database - MySQL 
// MySQL host 
$db_host = 'localhost'; 

// MySQL username 
$db_username = 'myuser'; 

// MySQL password 
$db_password = 'mypassword'; 

// MySQL database 
$db_database = 'mydb'; 

// Error to display at the top of the page if a connection problem occured 
$db_connect_error = 'Sorry, we\'re experiencing connection problems.'; 
?> 

connect.php

<?php 
mysql_connect($db_host, $db_username, $db_password) or die($db_connection_error); 
mysql_select_db($db_database) or die($db_connection_error); 
?> 

我得到的错误是

Notice: Undefined variable: db_host in C:\xampp\htdocs\w\php-site\core\db\connect.php on line 2 

Notice: Undefined variable: db_username in C:\xampp\htdocs\w\php-site\core\db\connect.php on line 2 

Notice: Undefined variable: db_password in C:\xampp\htdocs\w\php-site\core\db\connect.php on line 2 

Warning: mysql_connect(): Access denied for user ''@'localhost' (using password: NO) in C:\xampp\htdocs\w\php-site\core\db\connect.php on line 2 

Notice: Undefined variable: db_connection_error in C:\xampp\htdocs\w\php-site\core\db\connect.php on line 2 

对不起,这么长的帖子,但我真的希望有人能帮帮我!

+3

,什么是在'DB \ connect.php'? – Mchl 2013-03-10 22:12:40

+0

很抱歉现在加了connect.php – 2013-03-10 22:14:53

+0

如果你用'require __DIR__'替换'require'config.php';'会怎么样? '/config.php';'? – Niko 2013-03-10 22:15:56

回答

1

您似乎在包含路径或index.php目录中有另一个名为config.php的文件。解释为in the documentation

根据给定的文件路径包含文件,或者如果没有给定文件路径,则指定include_path。如果在include_path中找不到该文件,include将最终在失败之前检入调用脚本自己的目录和当前工作目录。

这个问题可以通过指定该文件的绝对路径很容易解决,即:

require(__DIR__ .'/config.php');