【问题标题】:Nested include with PHP嵌套包含与 PHP
【发布时间】:2012-07-12 14:01:57
【问题描述】:

我在使用嵌套包含时遇到问题。虽然我看到有很多类似的问题,但它们似乎没有帮助。

通常我对包含没有问题,但最近我一直在尝试新的东西,但我无法让嵌套包含工作。

一种解决方案:php nested include behavior

基本设置:

  • index.php 包含'/include/header.php'
  • header.php 包含“/resources/login/index_alt.php”
  • index_alt.php 包含“/resources/login/index_auth.php”
  • index_auth.php 包括 '/class/Login.class.php' 和 '/class/Connection.class/php'

我实际上并没有这样写路径(它是为了理解深度)。 这就是它在页面上的外观。

index.php

  • include('include/header.php');

header.php:(除了 /resources/...,每个深度级别都包含标题)

  • include('../resources/login/index_alt.php');

index_alt.php

  • include('index_auth.php');

index_auth.php

  • include('../../class/Login.class.php');
  • include('../../class/Connection.class.php');

在某些深度级别,头文件被接受,但包含嵌套将不会...

【问题讨论】:

  • 我建议你重新考虑你的包含策略,包括文件本身包含文件,而这些文件又可能包含文件,从长远来看,随着依赖关系变得越来越混乱,只会导致麻烦。您最好在一个地方完成所有包含,即直接访问的脚本。更好的是,如果您使用面向对象的方法,则可以使用自动加载器。
  • 查看 include_once() 或 require_once()。这样您就不必担心多次包含单个文件。
  • @GordonM 感谢您的评论。它并不像你想象的那么糟糕。有了这个额外的功能,我需要已经在别处实现的代码。

标签: php include nested require


【解决方案1】:

不要使用 ../ 遍历目录树,而是使用 dirname(__FILE__)。此外,您可能希望 include_once() 或 require_once() 避免其他潜在问题:

index.php:

include('include/header.php');

header.php:

include(dirname(dirname(__FILE__)) . '/resources/login/index_alt.php');

(注意 dirname(__FILE__) 将返回当前目录,但 dirname(dirname(__FILE__)) 将返回父目录)

【讨论】:

    【解决方案2】:

    假设文件系统看起来像这样..

    /www
       include/header.php
       class/Login.class.php
       class/Connection.class.php
       resources/login/index_alt.php
       resources/login/index_auth.php
       index.php
    

    这意味着

    index.php: include(__DIR__ . '/include/header.php');
    header.php: include(__DIR__ . '/../resources/login/index_alt.php');
    index_alt.php:  include(__DIR__ . '/index_auth.php');
    

    等;见http://php.net/manual/en/language.constants.predefined.php

    【讨论】:

      猜你喜欢
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      相关资源
      最近更新 更多