2009-07-20 170 views
0

Im新的MVC和我重新做了很多我的代码。require_once问题与模板

我有master.php(指数),其中有:

<?php require_once("header.php"); ?> 

两个master.phpheader.php是在同一文件夹但我得到以下错误:

Warning: require_once(1) [function.require-once]: failed to open stream: No such file or directory in /Users/MyName/Sites/MySite/Views/master.php on line 15

Fatal error: require_once() [function.require]: Failed opening required '1' (include_path='.:') in /Users/MyName/Sites/MySite/Views/master.php on line 15

这并没有发生之前。 (文件全部在根文件夹中)。我没有看到问题出在哪里,因为它们在同一个文件夹中 - 我不必返回'../'或引用任何其他文件夹。我在这里错过了什么?

谢谢。

+1

从它没有错误看起来像试图要求“header.php”它看起来像它试图要求“1”。你真的在第15行显示的是哪一行?它可能会帮助你,如果你张贴更多的代码 – Cfreak 2009-07-20 14:37:54

+0

是的,它是第15行的确切代码:<?php require_once(“header.php”)或die; ?> – asdfasdfasdfasdf 2009-07-20 14:47:50

回答

5

在您的评论你说你的代码是:

<?php require_once("header.php") or die; ?> 

请尽量留出了“或死“ - > IST是没有必要的,因为如果没有找到该文件,require_once会触发致命错误。

编辑: 我测试了它,省去了“或死”,它会工作。

编辑2:解释为什么会这样: 上面的代码也可以这样写:

require_once (("header.php") or die()); 

因为require_once不是一个函数,但是在PHP的声明中,括号是可选的,PHP解释上面是一个布尔表达式,其中字符串“header.php”被赋值为布尔值“true”。 True被转换为一个字符串(导致“1”),并且该字符串被传递回来以便需要一次。

所以上面的代码被解释为

require_once("1") 

这里是如何它被解释一步一步:

(("header.php") or die()) = (TRUE or die()) 
(TRUE or die()) = TRUE 
(string) TRUE = '1'; 

希望这有助于;)

1

PHP开始在根文件夹中寻找'header.php',并且找不到它。如果是在同一目录作为当前的脚本,你倒是应该使用魔术常量__DIR__

<?php require_once __DIR__ . '/header.php'; ?> 
+0

由于header.php和master.php都在同一个目录中,并且包含路径有'。'在这里,这不应该是必需的。 – MitMaro 2009-07-20 14:46:36

+0

当前目录(include_path =。)是脚本被调用的路径,而不是目录,脚本所在。 – soulmerge 2009-07-20 14:48:52

1

这可能是因为master.php被列入或另一个脚本文件,它是不是在同一个目录中所需 as header.php。也就是说,当你访问索引时,你知道哪个文件被调用/解析吗?

看看在documentationinclude(),这也适用于require()

Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries, current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/

更新

为了解决一些评论:我并没有说包括()将改变CWD。我在说,如果CWD不是master/header.php所在的那个,那可能是问题所在。

例如,假设您在与master.phpheader.php不同的文件夹中有index.php;它包含或要求master.php使用正确的路径。现在,master.php具有声明:

<?php require_once("header.php"); ?> 

然而,在这一点上CWD 不含header.php,因为CWD是,index.php

要解决此问题,需要使用当前脚本的CWD到header.php的正确路径调用require_once,而不是从master.php开始的路径。

0

你需要有15行,因为这:

<?php (require_once("header.php")) or die(); ?> 

但是从何时起头。PHP是没有找到需要是致命的,那么你应该有:

<?php (include_once("header.php")) or die(); ?> 

<?php require_once("header.php"); ?>