本文介绍了PHP:无法声明类,因为该名称已被使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有5个脚本,比方说:database.php,parent.php,child1.php,child2.php和somescript.php

I have 5 scripts, let's say: database.php, parent.php, child1.php, child2.php and somescript.php

parent.php类如下:

parent.php class looks like this:

include 'database.php';

class Parent {
    public $db;
    function __construct() {
        $this->db = new Database();
    }
}

child1和child2类如下:

child1 and child2 classes looks like this:

include 'parent.php';

class Child1 extends Parent {
    function __construct() {
        parent::__construct();
    }

    function useDb() {
        $this->db->some_db_operation();
    }
}

问题

当我尝试在childscript.php中同时包含child1和child2时,它返回以下错误:

When I try to include both child1 and child2 in somescript.php, it returns the following error:

但是,如果我仅包含一个文件(child1或child2),则效果很好.

But if I include only a single file (child1 or child2), it works great.

我该如何纠正?

推荐答案

您要使用 include_once() require_once().另一种选择是使用正确的顺序创建一个包含所有班级包含内容的附加文件,这样他们就不需要自己调用包含内容了:

you want to use include_once() or require_once(). The other option would be to create an additional file with all your class includes in the correct order so they don't need to call includes themselves:

"classes.php"

"classes.php"

include 'database.php';
include 'parent.php';
include 'child1.php';
include 'child2.php';

那么您只需要:

require_once('classes.php');

这篇关于PHP:无法声明类,因为该名称已被使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:02