PHP:无法声明类,因为该名称已被使用 [英] PHP: cannot declare class because the name is already in use

查看:177
本文介绍了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:

无法声明类数据库,因为该名称已在中使用 第4行(这是包含单词类数据库"的行)上的database.php

cannot declare class Database because the name is already in use in database.php on line 4 (this is the line which contains words 'class Database')

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

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

我该如何纠正?

推荐答案

您要使用 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:无法声明类,因为该名称已被使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆