【问题标题】:Nesting include_once problems嵌套 include_once 问题
【发布时间】:2014-01-17 12:26:47
【问题描述】:

这是我的目录树:

  • /
    • index.php
  • 包括/
    • functions.php
    • head.php
    • connect.php
  • 子/
    • index.php

在我的 head.php 和 connect.php 中都有:

include_once 'include/functions.php';

我的根目录下的index.php包含这两个:head.php和connect.php,如下:

include_once 'include/connect.php';
include_once 'include/head.php;'

但是,当我在 sub/ 中的 index.php 包含 functions.php 和 head.php 时,它们将无法同时包含 functions.php。 这是我在 sub/index.php 中包含的方式:

include_once '../include/connect.php';
include_once '../include/head.php';

如果我将 head.php 和 connect.php 更改为:include_once '../include/functions.php';

sub/index.php 将正常包含所有内容,但根目录中的 index.php 将无法加载 functions.php。

我该如何解决这个问题?

PHP 版本:5.2.*

【问题讨论】:

  • 认为您的 head.phpconnect.php 包含语句中有错误。 include_once 'include/functions.php'; 应该是include_once 'functions.php'; 因为head.php 和connect.php 与functions.php 在同一个目录中?如果我错了,请纠正我:P
  • @vincent-wilkie 谢谢!这就是它一直遇到的问题...谢谢!

标签: php


【解决方案1】:

您可以在根文件中定义包含路径的常量,然后在所有其他文件中使用该常量:

define( "INCLUDE_PATH",  dirname(__FILE__) . '/include/' );

// some other file
include_once INCLUDE_PATH . 'functions.php';

最好在根文件夹中有一个像 config.php 这样的文件,其中定义了包含路径等全局设置。这样您就不必再关心相对路径了,如果将来您决定更改文件夹结构,而不是更改所有文件中的路径,只需更改包含常量。

【讨论】:

    【解决方案2】:

    错误


    head.phpconnect.php 中包含语句错误

    include_once 'include/functions.php';


    修复


    include_once 'functions.php';

    include_once __DIR__ . 'functions.php'; //PHP 5.3 or higher

    include_once dirname(__FILE__) . 'functions.php'; //PHP 5.2 or lower


    原因


    head.phpconnect.phpfunctions.php 位于同一文件夹中

    正如@Schleis 所建议的,使用__DIR__ (PHP 5.3+) 或dirname(__FILE__); (PHP 5.2-) 将允许包含相关文件。

    【讨论】:

    • 谢谢!投票并检查了这个。
    【解决方案3】:

    在包含语句中使用常量__DIR__,然后相对于它移动。所以在 sub/index.php 你会做include_once __DIR__ . '../include/connect.php'

    __DIR__ 是一个常量,它是您所在文件的目录。

    http://php.net/manual/en/language.constants.predefined.php

    如果你使用的是phpdirname(__FILE__)来获得同样的东西。

    【讨论】:

    • __DIR__ 自 PHP 5.3.0 起添加 :)
    • 查看更新,可以使用dirname(__FILE__)获取以前php版本中的目录
    【解决方案4】:

    我建议使用chdir() 函数在每个文件中设置您的Web 项目根目录,这样您就无需考虑您当前位于何处以及需要多少个后备目录../

    使用示例:

    chdir($_SERVER['DOCUMENT_ROOT']);
    

    【讨论】:

      猜你喜欢
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2018-02-20
      相关资源
      最近更新 更多