Fatal error: Cannot redeclare class 原因分析與解決辦法

來源:互聯網
上載者:User

錯誤提示

Fatal error: Cannot redeclare class ….

從字面來看也很好理解,說明是重複定義了類,找了一下自己的代碼,是因為存在同名的類導致的,修改了類名就好了。

原因分析

1.在同一個檔案中重複聲明了兩次同名的類:
例如:

 

 代碼如下 複製代碼
<?php  
class Foo {}  
 
// some code here  
 
class Foo {}  
?> 

在第二個 Foo 的地方就會報錯。

解決:去掉第二個Foo,或者重新命名。

為了防止重複定義,可以在定義一個新的類的時候判斷一下這個類是否已經存在:

 

 代碼如下 複製代碼
if(class_exists('SomeClass') != true)  
{  
   //put class SomeClass here  

if(class_exists('SomeClass') != true)
{
   //put class SomeClass here
}


2.重複包含相同的類檔案:

例如:對於某個類檔案some_class.php,在a.php中

 代碼如下 複製代碼

include "some_class.php"; 
include "some_class.php";

在b.php中

 代碼如下 複製代碼


include "a.php";  
include "some_class.php"; 
include "a.php";
include "some_class.php";

就會報錯。

解決:將上述的include全部替換為include_once

3.該類為PHP類庫中內建的類。

判斷方法:在一個空檔案中寫入

 

 代碼如下 複製代碼
<?php  
class Com  
{  
 
}  
?> 

這時候提示Cannot redeclare class Com,說明這個類就是PHP內建的類。不能使用。

另外,要避免使用太福士化的類名,比如Com,這個類在Linux使用可能是正常的,在Windows環境卻無法運行。


再記一個網上找到的解決方案,可能在某些場合有用,先記著

 代碼如下 複製代碼


if (!class_exists('pageModule')){    
require_once(PATH_site.'fileadmin/scripts/class.page.php');
 }

上面的辦法不適用於使用了php __autoload類載入的方法 ,但己經可以解決辦法問題了,__autoload是自動載入的我們只要把相同類名找出來然後重新命名即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.