首页 > 解决方案 > 使用抽象类“找不到类”的 PHP 错误

问题描述

我有一个简单的脚本,其中包括:

出于某种原因,我收到此错误:

( ! ) Fatal error: Uncaught Error: Class 'Products' not found in 

D:\xampp\htdocs\ds2\classes\GetAllProducts.php on line 4
( ! ) Error: Class 'Products' not found in D:\xampp\htdocs\ds2\classes\GetAllProducts.php on line 4
Call Stack
#   Time    Memory  Function    Location
1   0.4119  410648  {main}( )   ...\index.php:0
2   0.4129  414904  include_once( 'D:\xampp\htdocs\ds2\classes\GetAllProducts.php' )    ...\index.php:3

在此处输入图像描述 这是我的代码:

索引.php

include_once 'abstract/Products.php';
include_once 'classes/GetAllProducts.php';


$customer = new GetAllProducts();
$customer->allData();

摘要/Products.php

<?

    abstract class Products {
        public $data = array(
            array(
                'id' => 1,
                'title' => 'title 1',
                'desc' => 'desc 1'
            ),
            array(
                'id' => 2,
                'title' => 'title 2',
                'desc' => 'desc 2'
            ),
            array(
                'id' => 3,
                'title' => 'title 3',
                'desc' => 'desc 3'
            )
        );
     
    }

类/GetAllProducts.php

<?php

class GetAllProducts extends Products {

    public function allData() {
        $this->data;
        foreach($this->data as $product){
            echo '
            <article id="product-'.$product['id'].'" class="product">
                <h2 product__title="">'.$product['id'].'</h2>
                <picture product__image="'.$product['title'].'">
                    <source media="(min-width:768px)" srcset="https://picsum.photos/200/300">
                    <img src="https://picsum.photos/200" alt="Flowers" style="width:auto;">
                </picture>
                <button class="product__button" role="button">לצפיה במוצר</button>
            </article>';
        }
    }
}

标签: phpinheritanceabstract-class

解决方案


您必须将抽象类包含到GetAllProducts.php文件中,因为您在该文件中使用抽象类,而不是在index.php.

<?php
include_once 'abstract/Products.php';

class GetAllProducts extends Products {}

推荐阅读