【问题标题】:How to access correctly classes from directories/subdirectories?如何从目录/子目录中正确访问类?
【发布时间】:2021-10-09 10:44:01
【问题描述】:

当我尝试从 account/index.php 内部访问 includes/config.php 时,出现以下错误:

警告: include(classes/user.php):打开流失败:/var/www/htdocs/dashboard/includes/config.php 中没有这样的文件或目录 第 6

警告: include():无法在 /var/www/ 中打开“classes/user.php”以包含 (include_path='.:/usr/share/php') htdocs/dashboard/includes/config.php6

我正确定义了路径,但是当index.php访问config.php时,我认为config.php在调用config.php中的类时出现目录问题,我找不到解决方法。

提前致谢。

这是文件夹结构

App/
├─ account/
│  ├─ index.php
├─ classes
├─ includes/
│  ├─ config.php
├─ index.php

index.phpaccount/index.php

<?php
require('../includes/config.php');
?>

config.phpincludes/config.php

<?php
ob_start();
session_start();

//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
include('classes/slug.php');
$user = new User($db);
?>

【问题讨论】:

  • 我猜你需要遍历一个目录来包含你的内容,即include('../classes/user.php);
  • 但是这次主根目录下的 index.php 抛出了同样的错误。那么如何将所有东西连接在一起呢? @Gowire

标签: php


【解决方案1】:

正如@Sohrab 所说,你需要给它绝对路径。您可以使用__DIR__ 解决此问题。 (文件的目录)了解更多关于DIR

你应该像这样使用它:

require(__DIR__.'/../includes/config.php');

也在 config.php 和其他文件中:

include(__DIR__.'/../classes/user.php');
include(__DIR__.'/../classes/phpmailer/mail.php');
include(__DIR__.'/../classes/slug.php');

【讨论】:

    【解决方案2】:

    配置文件在其目录中查找文件。 您应该将代码更改为:

    <?php
    ob_start();
    session_start();
    
    //include the user class, pass in the database connection
    include('../classes/user.php');
    include('../classes/phpmailer/mail.php');
    include('../classes/slug.php');
    $user = new User($db);
    ?>
    

    【讨论】:

    • 我试过了,但主根目录中的 index.php 会抛出与 account/index.php 相同的错误
    • 如果你想从主目录访问另一个目录,你可以给它绝对路径(以'/'开头)。我建议你了解绝对路径和相对路径。
    • 好的,谢谢,我会学习绝对路径的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多