第一种解决方法:
是对重复定义的两个类的其中一个重命名。第二种方法是:
如果这些类是include/require进来的,那么去掉多余的include/require,或者把include/require分别改成include_once/require_once。注意,这两种解决方法适用的情况不同。
如果两个php文件定义了两个功能不同的类,但是名字相同,应该用第一种方法解决。
如果是不小心把同一个php文件include或者require了多次,那么应该用第二种方法解决。
示例:
文件C1.php内容内容如下:
<?php
class C1 {
public function say() {
return 'hello';
}
}
文件test.php内容若如下:
<?php
require 'C1.php';
require 'C1.php';
会有Cannot redeclare class的错误。
文件test.php内容若如下:
<?php
include 'C1.php';
include 'C1.php';
会有Cannot redeclare class的错误。
文件test.php内容若如下:
<?php
require_once 'C1.php';
require_once 'C1.php';
或者:
<?php
include_once 'C1.php';
include_once 'C1.php';
则不会报错。
现在新建文件C2.php,内容如下:
<?php
class C1 {
public function say() {
return 'hello';
}
}
修改test.php为以下内容:
<?php
include_once 'C1.php';
include_once 'C2.php';
会有Cannot redeclare class的错误。
这时候,如果不想更改C1.php和C2.php的类名,那么可以使用命名空间。
如C1.php内容为:
<?php namespace foo;
class C1 {
public function say() {
return 'hello';
}
}
?>
<?php namespace bar;
class C1 {
public function say() {
return 'hello world';
}
}
<?php
require_once './C1.php';
require_once './C2.php';
$c1 = new \foo\C1();
echo $c1->say();
$c2 = new \bar\C1();
echo $c2->say();
运行结果如下:
$ /usr/bin/php C1_C2_test.php
hellohello world
关于命名空间:
http://my.oschina.net/u/867608/blog/127351
http://my.oschina.net/Jacker/blog/32943