繁体   English   中英

包含来自另一个目录 php 的类文件

[英]include class files from another directory, php

试图为classapi等创建一个文件结构。但是当我尝试将一个类包含到api/文件中时,问题发生了......看起来我无法正确给出文件路径。 但是找不到哪里出了问题。

目录和文件结构如下图所示。

在此处输入图片说明

插入类

class Insert extends Dbc {

    public function getProjects(){

        $sql = "SELECT * FROM projects";
        $stmt = $this->connect()->query($sql);
        while($row = $stmt->fetch()){
            $row["project_name"] . "<br>";
        }

    }

}

自动加载公司

spl_autoload_register('autoloader');

function autoloader($className){
    $path = "classes/";
    $extension = ".class.php";
    $fullPath = $path . $className . $extension;

    if (!file_exists($fullPath)) {
        return false;
    }

    include_once $fullPath;
}

最后, /api文件projects.api

<?php 
    include "../inc/autoload.inc.php";
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <?php 
            $projects = new Insert(); 
            echo $projects->getProjects(); 

    ?> 
</body>
</html>

但这是我收到 500 错误的原因。 当我在$projects = new Insert();上使用 try 和 catch 时$projects = new Insert(); 在 api 文件中。 它说找不到class ......这意味着include "../inc/autoload.inc.php"; 工作不正常?

我解决了这个问题。 错误是我没有在自动加载文件中包含该类。 所以它没有找到类..这是新的autoload.inc.php

spl_autoload_register('autoloader');

include "../classes/insert.class.php";

function autoloader($className){
    $path = "../classes/";
    $extension = ".class.php";
    $fullPath = $path . $className . $extension;

    if (!file_exists($fullPath)) {
        return false;
    }

    include_once $fullPath;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM