首页 > 解决方案 > 如何从目录/子目录中正确访问类?

问题描述

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

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

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

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

提前致谢。

这是文件夹结构

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

帐户/index.php中的index.php

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

包含/config.php中的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);
?>

标签: php

解决方案


正如@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');

推荐阅读