【问题标题】:PHP Relative paths for require filePHP 需要文件的相对路径
【发布时间】:2014-09-05 09:16:14
【问题描述】:

我一直在讨论这两个主题:

并且无法使我的脚本工作,所提供的方法都不起作用,或者我做错了什么。

无论如何,这就是我的问题发生的地方:

Root/                                   //this is root location for server
APP/                                    //this is root location for script
Root/APP/core/init.php                  //this is where I include classes and functions from
Root/APP/classes/some_class.php         //this is where all classes are
Root/APP/functions/some_function.php    //this is where all functions are

显然我需要在任何地方都包含init.php,所以我在每个文件中都这样做了:

require_once 'core/init.php';

在我决定为这样的管理文件创建一个位置之前,它一直在工作:

Root/APP/Admin/some_admin_file.php

当我以这种方式包含 init 时:

require_once '../core/init.php';

脚本无法打开函数,APP/Core/ 文件夹中没有此类文件 所以我使用了上面主题中介绍的 DIR 方法,甚至发生了更奇怪的事情,错误:

APP/Core/classes/Admin/中没有这样的文件

那是什么? :D 我迷路了,有人能帮忙吗;)

【问题讨论】:

  • 检查字母的大小写,它们是这样大写的: APP/Core/ 或 APP/core/ ,其中一个是错误的

标签: php


【解决方案1】:

包含路径是相对于当前工作目录的,可以使用getcwd()检查;当您的项目变得更大时,这可能会导致许多问题。

为了使包含路径更稳定,您应该使用__DIR____FILE__ 魔术常量;例如,在您的特定情况下:

require_once dirname(__DIR__) . '/core/init.php';

dirname(__DIR__) 表达式实际上是当前正在运行的脚本的父目录。

顺便说一句,__DIR__ 也可以写成dirname(__FILE__)

【讨论】:

  • 如果我在 admin 文件夹中的 admin 文件中执行此操作 require_once dirname(__DIR__) . '/core/init.php';,我会收到此错误:Warning: require_once(functions/my_function.php) [function.require-once]: failed to open stream: No such file or directory in /APP/core/init.php 所以就像尝试从核心文件夹打开函数/函数
  • @PatrickMevia 是的,好吧,这只是意味着问题也必须在那里解决:)
猜你喜欢
  • 2012-12-03
  • 2012-04-21
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 2013-08-06
  • 2015-02-23
  • 1970-01-01
  • 2014-01-15
相关资源
最近更新 更多