重组代码结构是给我一个包括问题在php


Restructuing the code structure is giving me an include issue in php

我重新构造了我已经工作的代码。我之前的目录结构如下:

  • web
    • css
      • style.css
    • 模型
      • db_functions.inc
    • 视图
      • view_functions.inc
    • 控制器
    • index . php

下面是正常工作的代码片段:

<?php
    $pageTitle = "Citee.me";
    //include view functions
    include ('view/view_functions.inc');
    //incldue db functions
    include ('model/db_functions.inc');
    doHtmlHeader($pageTitle);
    doBody();
    testMySQL();
    doHtmlFooter();
?>

我现在将代码重组为:

  • web
    • 模型
      • db_functions.inc
    • 视图
      • view_functions.inc
    • 控制器
  • 公共
    • css
      • style.css
    • js
    • index . php

现在我修改了我的index.php代码如下(我注释掉了db函数以缩小问题):

 <?php
    $pageTitle = "Citee.me";
    //include view functions
    include ('/citee/web/view/view_functions.inc');
    //incldue db functions
    //include ('./model/db_functions.inc');
    doHtmlHeader($pageTitle);
    //doBody();
    //testMySQL();
    doHtmlFooter();
?>

我得到错误:

PHP Warning:  include(/citee/web/view/view_functions.inc): failed to open stream: No such file or directory in /Library/WebServer/Documents/citee/public/index.php on line 6
PHP Warning:  include(): Failed opening '/citee/web/view/view_functions.inc' for inclusion (include_path='.:/usr/lib/php') in /Library/WebServer/Documents/citee/public/index.php on line 6
PHP Fatal error:  Call to undefined function doHtmlHeader() in /Library/WebServer/Documents/citee/public/index.php on line 9

不知道为什么我得到这个错误。我的include路径错了吗?我尝试了不同的组合,但都没有效果。

提前感谢。

PHP是你的朋友,它给了你执行代码的完整路径:

/Library/WebServer/Documents/citee/

/citee/

不能访问根目录以外的文件并不意味着PHP不会访问根目录以外的文件

在第二个例子中,你的路径是绝对的,并且以"/cite "开头。但是错误信息显示你的文件在"/Library/WebServer/Documents/citee"。如果使用的是绝对路径,则必须使用正确的路径

PHP抱怨路径/citee/web/view/view_functions.inc不存在,我也怀疑它。你会cd /citee/web/view/吗?我打赌不会。

如果您试图访问它,您可以使用相对文件路径(这是一个更好的实践,考虑将来部署到不同的结构化服务器文件系统)。

所以,代替/citee/web/view/view_functions.inc,你可以从index.php的路径工作到正确的相对路径:../web/view/view_functions.inc (..代表"在树中向上一个目录",这意味着它将进入你的"citee"文件夹,然后访问"web"文件夹,等等)