我正在寫我的第一個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 Blackbourn在WP-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 isinclude()
-ed inside another function at the point where it is activated unlike at others times when the plugin file is simplyinclude()
-ed. Phew. Bit of an odd one to get your head around but there we go.
我以爲我做了什麼描述,但我仍然得到錯誤。我也嘗試了其他所有可能的地方組合$thumbs
...
請問您可以在代碼片段中標記文件/dev/site/wp-content/plugins/thumbs-up/thumbs-up.php的第160和162行嗎? – VolkerK 2009-07-28 16:05:50
已將行號添加到適當的行。 – 2009-07-28 16:22:19
沒關係我在看完全是錯誤的東西.. – 2009-07-28 16:33:04