【发布时间】:2012-04-06 11:13:32
【问题描述】:
您好,我遇到了一个未设置变量的问题。如果我使用的是相对路径,它可以正常工作,但是当使用绝对路径时,php 说它没有设置。
<?php
define('DS', DIRECTORY_SEPARATOR);
define('SITE_ROOT', 'G:' . DS . 'htdocs' . DS . 'www');
define('LAYOUT_PATH', SITE_ROOT . DS . 'layout');
require('function.php');
$user = new User();
$user->set_username('johndoe');
require_layout_template('header.php');
?>
在我的header.php:
<?php
//if ( isset($user) ) {
echo $user->get_username();
//}
?>
上面的结果是这个错误:
Notice: Undefined variable: user in G:\htdocs\www\layout\header.php
但是,如果我使用相对路径,一切正常。
我在 windows 环境中的 localhost 上运行,并在 PHP 版本 5.3.5 中运行。
更新:
我没有包含require_layout_template 是我的错。我在function.php 中包含了这个函数来处理require 的必要细节。
<?php
//function.php
function require_layout_template($template) {
global $user; // added this to solve the problem.
require(LAYOUT_PATH . DS . $template);
}
?>
我已经为变量$user添加了必要的全局变量。
感谢@strkol 的想法。
【问题讨论】:
-
变量范围不取决于文件是包含在绝对路径还是相对路径中,所以你的问题出在其他地方
-
在你的 header.php 中尝试做一个 echo $_SERVER['REQUEST_URI'];怎么说?
-
能否在 header.php 中添加这一行,尝试两种情况并发布输出:
print_r(get_included_files()); -
@strkol 我想我找到了罪魁祸首。谢谢你的想法。
标签: php variables undefined include-path