关于PHP中Cann't redeclare class的错误

include.class.php
<?php

class IncludeTest {
}

?>

test.php
<?php
//报错
//Fatal error: Cannot redeclare class IncludeTest in D:\myphp\research\include_test\include.class.php on line 3
//require('include.class.php');
//require('include.class.php');

//报错
//Fatal error: Cannot redeclare class IncludeTest in D:\myphp\research\include_test\include.class.php on line 3
//require_once('include.class.php');
//require('include.class.php');

//不报错
//require('include.class.php');
//require_once('include.class.php');

//不报错
require_once('include.class.php');
require_once('include.class.php');

//总结,两次加载同一文件,只要后面一个用require_once,则不报错。
?>

还有一种情况,就是在多个地方加载了同一个类,但是即使用了incluce_once或require_once仍然会报错(暂时不知道是什么原因导致的),此时有一种办法可以解决,那就是在加载之前用class_exists判断一下,且第二参数用false,这样可以提高性能,用class_exists判断一下后,就不会报Cann't redeclare class的错误了。

例如if (!class_exists('Smarty', false)) include_once('/path/to/Smarty.class.php');

================================================================================================================

  

posted on 2014-08-04 14:22  < Angus >  阅读(464)  评论(0编辑  收藏  举报

导航