2009-07-28 44 views
1

我正在寫我的第一個wordpress插件,我試圖創建一個函數,當插件被激活時被調用。WordPress的register_activation_hook()+全局變量+類:不能重新聲明

目前,它看起來像這樣:

class ThumbsUp { 

... 

} 

global $thumbs; 
function thumbs_install() { 
    //global $thumbs; 
    $thumbs = new ThumbsUp(); /* Line 160 */ 
    $thumbs->installThumbsUp(); 
}        /* Line 162 */ 

// When plugin is activated -> install. 
register_activation_hook(__FILE__,'thumbs_install'); 

但是,當我激活插件我收到以下錯誤:

Plugin could not be activated because it triggered a fatal error.

Fatal error: Cannot redeclare thumbs_install() (previously declared in /dev/site/wp-content/plugins/thumbs-up/thumbs-up.php:160) in /dev/site/wp-content/plugins/thumbs-up/thumbs-up.php on line 162

我GOOGLE看去,它談到作爲一個變量的作用域問題,但我找不到任何答案的例子,我的PHP不夠強大,不足以將討論轉化爲代碼。

這裏的the solution described by John BlackbournWP-hackers ML

Any global variables that you want to reference inside the function that is called by register_activation_hook() must be explicitly declared as global inside the main body of the plugin (ie. outside of this function). The plugin file is include() -ed inside another function at the point where it is activated unlike at others times when the plugin file is simply include() -ed. Phew. Bit of an odd one to get your head around but there we go.

我以爲我做了什麼描述,但我仍然得到錯誤。我也嘗試了其他所有可能的地方組合$thumbs ...

+1

請問您可以在代碼片段中標記文件/dev/site/wp-content/plugins/thumbs-up/thumbs-up.php的第160和162行嗎? – VolkerK 2009-07-28 16:05:50

+0

已將行號添加到適當的行。 – 2009-07-28 16:22:19

+0

沒關係我在看完全是錯誤的東西.. – 2009-07-28 16:33:04

回答

1

對此問題有一個更一般的答案:從register_activation_hook註冊的函數運行的代碼中出現的每個錯誤將顯示爲「cannot redeclare ...」而不是實際的錯誤。我懷疑這是因爲WordPress在調用激活鉤子時包含插件文件的方式。

+0

這個答案是錯誤的和誤導。在作爲參數傳遞給'register_activation_hook'的回調函數代碼中發生的錯誤將顯示爲它們的內容,而不是*因爲不能重新聲明... *錯誤。當名稱在已存在的範圍內重新聲明時,會發生重新聲明錯誤。這也是在這裏發生的事情。 – 2016-06-28 21:54:56

0

注:如果您通過搜索引擎來到這裏進行了關於WordPress的register_activation_hook()global變量的結果,請跳到這個答案的第二部分。


背後此錯誤信息的理由是,該thumbs_install名稱第一次創建而include()編一次,然後第二次。

其中的一個,include()activate_plugin()範圍內由/wp-admin/includes/plugin.php on line 560編輯;另一個很可能是你的做法:WordPress不包括任何尚未激活的插件,並且只在activate_plugin()中包含插件文件一次。

而且,我無法重現你在你的問題粘貼代碼中的問題,但我得到了與以下版本的ThumbsUp類的正是這樣的錯誤:

class ThumbsUp { 
    function installThumbsUp() { 
     include(__FILE__); 
    } 
} 

但是,因爲你沒有與我們分享您的ThumbsUp課程的代碼,我無法幫助您進一步處理這個直接的問題。

值得注意的是,第一(活化)之前包括在activate_plugin()功能插件的目的是防止從WordPress的,因爲未激活的插件崩潰;因此,額外的include()require()很可能發生在您插件代碼的其他地方(不一定在本地範圍內)。


關於使用傳遞給register_activation_hook()回調函數global變量;主要是因爲插件的第一個include()(在激活期間)發生在函數(activate_plugin())的範圍內,所以有必要在它們被訪問的插件的每個位置聲明這些變量global

這意味着:他們需要在插件文件的範圍(通常認爲變量已經是全局變量)中明確設置爲global

這是因爲上述變量定義,第一次啓動,activate_plugin()範圍中,並除非設置全局明確,他們不會在全球範圍內存在。

實施例:

<?php 
global $myvar; 
$myvar = 'some value'; 

function using_myvar() { 
    global $myvar; 
    some_processing_with($myvar); 
} 

register_activation_hook(__FILE__, 'using_myvar'); 

諾塔好處:由於第一激活後,該插件被認爲是 '安全的' 是全局include() ED;只有在上述回調中使用的變量在文件範圍內聲明爲全局變量纔是必要的。