簡體   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