简体   繁体   English

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

[英]include class files from another directory, php

Trying to make a file structure for class , api and etc. But when I try to include a class into api/ file, problem happens... it's look like I can't give the file path's correctly.试图为classapi等创建一个文件结构。但是当我尝试将一个类包含到api/文件中时,问题发生了......看起来我无法正确给出文件路径。 But couldn't find what is wrong.但是找不到哪里出了问题。

the directory and file structure is like image below.目录和文件结构如下图所示。

在此处输入图片说明

Insert class插入类

class Insert extends Dbc {

    public function getProjects(){

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

    }

}

autoload inc自动加载公司

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;
}

and finally, /api file projects.api最后, /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>

But here is the thing I am getting a 500 error.但这是我收到 500 错误的原因。 AND when I use try and catch on $projects = new Insert();当我在$projects = new Insert();上使用 try 和 catch 时$projects = new Insert(); in api file.在 api 文件中。 It says can't find the class ... It means include "../inc/autoload.inc.php";它说找不到class ......这意味着include "../inc/autoload.inc.php"; not working correctly?工作不正常?

I solved the issue.我解决了这个问题。 The mistake was I didn't include the class inside the autoload file.错误是我没有在自动加载文件中包含该类。 So it doesn't find the class.. Here is the new 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