2013-01-18 44 views
0

我有下面的代碼。當我運行它,我得到錯誤:PHP從兩個不同的文件重新聲明類

Fatal error: Cannot redeclare class Google_Account in 
    /var/www/vhosts/example.com/httpdocs/google-api-php-client 
    /src/contrib/Google_AnalyticsService.php on line 379 

這是因爲無論是「Google_AdsenseService.php」和「Google_AnalyticsService.php」文件中有一個名爲類Google_Account。 Google_Account類的成員變量和函數在那些文件中是不同的。

我需要同時獲取AdSense和Google Analytics數據。所以我需要同時使用這兩種服務。我無法找到解除類聲明的方法。我怎樣才能一起使用這兩種服務?

include_once APP.'Vendor/google-api-php-client/src/Google_Client.php'; 
$client1 = new Google_Client(); 
$client1->setApplicationName('aaa'); 
$client1->setDeveloperKey('1234'); 
$client1->setRedirectUri('http://example.com/'); 

include_once APP.'Vendor/google-api-php-client/src/contrib/Google_AdsenseService.php'; 
$client1->setClientId('2345'); 
$client1->setClientSecret('4444'); 
$service1 = new Google_AdsenseService($client1); 
// some code that gets data from "$service1" 

$client2 = new Google_Client(); 
$client2->setApplicationName('aaa'); 
$client2->setDeveloperKey('1234'); 
$client2->setRedirectUri('http://example.com/'); 

include_once APP.'Vendor/google-api-php-client/src/contrib/Google_AnalyticsService.php'; 
$client2->setClientId('4567'); 
$client2->setClientSecret('5555'); 
$service2 = new Google_AnalyticsService($client2); 
// some code that gets data from "$service2" 
+0

[Namespacing](http://php.net/manual/en/language.namespaces.php)? –

+0

Someone http://stackoverflow.com/questions/1572159/undeclare-a-class-in-php說,這是不可能的un-declare classes – samayo

+0

這是不可能從內部註冊表中刪除類。這就是爲什麼你遵循[psr-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) –

回答

0

你有兩個選擇:

  1. 對於PHP 5.3+,你可以在文件的開頭添加一個命名空間。在此之後,您需要修復對修改後類中其他類的引用(異常將變爲::例外等)

  2. 您可以在文本編輯器中重命名類,這可能會更容易。只需在您最喜歡的文本編輯器中打開文件,然後使用全部替換。將Google_Client更改爲其他內容。有一個很好的變化,lib不會使用動態類構造和其他有趣的東西,所以你的快速重構代碼將工作。

1

您可以在contrib目錄中的每個文件的頂部添加不同的名稱空間。例如對於Google_AdsenseService.php文件,在頂部添加namespace Google\AdsenseService;

// Google_AdsenseService.php file 
namespace Google\AdsenseService; 

只要文件內容只引用同一文件中的內容,它就會起作用。只有當你訪問它時,你才能通過命名空間訪問它。像這樣,

$service1 = new Google\AdsenseService\Google_AdsenseService($client1); 
+0

感謝您的建議,但類的實現方式不同:http://code.google.com/p/google-api-php-client/source/browse/trunk/src/contrib /Google_AdsenseService.php#912和http://code.google.com/p/google-api-php-client/source/browse/trunk/src/contrib/Google_AnalyticsService.php#440 – trante

+0

@trante然後報告錯誤 –