【问题标题】:PHP: variable undefined in included or required filePHP:包含或所需文件中未定义的变量
【发布时间】: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


【解决方案1】:

一般来说,最好的方法是在站点上定义用户直接调用的根目录。所以所有索引站点,应该由用户直接寻址,而不是在其他 .php 文件中,包括或类等等。

index.php:
$rootdir = '../';

require_once($rootdir.'dir/other.php);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
  • 2017-01-22
  • 2012-10-29
  • 2012-04-18
  • 2015-08-29
  • 1970-01-01
  • 2019-12-30
相关资源
最近更新 更多