PHP: cannot redeclare class

2019-04-17 02:10发布

So I have 3 classes in this situation.

Connection.php
Engineer.php
Status.php

Both Engineer and Status classes actually use connection. Hasn't been a problem but now that I'm using both classes in a page I'm getting

Fatal error: Cannot redeclare class Connection

Is there a way round this? In both classes I need db access from the connection class.

Thanks,

Jonesy

标签: php class
6条回答
SAY GOODBYE
2楼-- · 2019-04-17 02:35

Use require_once() rather than require().

Or alternatively, use autoload, which saves you having to specify it loads of times.

I suspect the autoload functionality would be the best thing for you, assuming you're using a new-enough version of PHP (it requires 5.3).

查看更多
放我归山
3楼-- · 2019-04-17 02:40

You are probably using an unsafe class file inclusion method, such as require or include.

Try using include_once or require_once.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-04-17 02:41

Use require_once.

查看更多
Luminary・发光体
5楼-- · 2019-04-17 02:47

well, how are you including the Connection.php? try using require_once.

查看更多
霸刀☆藐视天下
6楼-- · 2019-04-17 02:50

instead of using include() use require_once() for importing Connection.php into Engineer.php and Status.php.

查看更多
干净又极端
7楼-- · 2019-04-17 03:00

You can always:

if(  !class_exists('Connection') ) {
    include('Connection.php');
}

or just use include_once(link) or require_once (link) or autoload mechanism

查看更多
登录 后发表回答