致命错误:无法重新声明类数据库 [英] Fatal error: Cannot redeclare class Database

查看:106
本文介绍了致命错误:无法重新声明类数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有胎儿错误消息说:

致命错误:无法在第3行的C:\ wamp \ www \ pets_new \ lib \ database.php中重新声明类数据库

Fatal error: Cannot redeclare class Database in C:\wamp\www\pets_new\lib\database.php on line 3

require_once("lib/message.php");
require_once("lib/user.php");

都连接到数据库类

课堂留言

<?php

require('database.php');

class Message{

班级用户:

<?php

require('database.php');

class User{

推荐答案

您在一个运行"中包含2个文件.这样思考:所有包含的文件都由PHP组合在一起以创建一个大脚本.每个includerequire都提取一个文件,并将其内容粘贴到该大脚本中.

You include 2 files in a single "run". Think of it like this: All the included files are put together by PHP to create one big script. Every include or require fetches a file, and pastes its content in that one big script.

您要包含的两个文件,都 require 属于同一文件,该文件声明了Database类.这意味着PHP生成的大脚本如下所示:

The two files you are including, both require the same file, which declares the Database class. This means that the big script that PHP generates looks like this:

class Message
{}
class Database
{}//required by message.php
class User
{}
class Database
{}//required by user.php

如您所见,类Database被声明了两次,因此出现错误.
目前,快速解决方案可以将require('database.php');语句替换为:

As you can see class Database is declared twice, hence the error.
For now, a quick fix can be replacing the require('database.php'); statements with:

require_once 'database.php';

检查以前是否未包含/需要该特定文件.如果以前已包含/必需,则PHP将不再需要它.
一个更确定,更好的恕我直言的解决方案是注册一个自动加载器函数/类方法,并让该代码处理事务.

Which checks if that particular file hasn't been included/required before. If it has been included/required before, PHP won't require it again.
A more definitive and, IMHO, better solution would be to register an autoloader function/class method, and let that code take care of business.

有关如何注册自动加载器的更多信息,请参见文档 .如果沿着这条路线走,您可能想在此处查看有关类名和名称空间的编码标准.如果符合这些标准,则无需编写自己的自动加载器,只需使用Symfony2的通用类加载器,或使用任何其他订阅PHP-FIG标准的框架(例如CodeIgnitor,Zend,Cake.). .命名)

More on how to register an autoloader can be found in the docs. If you go down this route, you'd probably want to take a look at the coding standards concerning class names and namespaces here. If you conform to those standards, you don't have to write your own autoloader, and can simply use the universal class loader from Symfony2, or any other framework that subscribes to the PHP-FIG standards (like CodeIgnitor, Zend, Cake... you name it)

这篇关于致命错误:无法重新声明类数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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