Adam Taylor Adam Taylor - 1 year ago 117
PHP Question

Wordpress register_activation_hook() + global variables + class: cannot redeclare

I'm writing my first wordpress plugin and I'm trying to create a function to be called when the plugin is activated.

Currently it looks like this:

class ThumbsUp {



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

// When plugin is activated -> install.

But when I activate the plugin I get the following error:

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

Fatal error: Cannot redeclare
(previously declared in
) in
on line 162

I've googled and looked and it's talked about as a variable scope issue but I can't find any examples of the answer and my php is not strong enough to translate the discussion into code.

Here's the solution described by John Blackbourn in the WP-hackers ML:

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

I thought I had done what is described but I still get the error. I've also tried every other combination of where I could possibly put the global

Answer Source

There is a more generic answer to this question: every error that occurs in the code that is run from the function registered with register_activation_hook will be shown as "cannot redeclare ... " instead of the actual error. I suspect this is because of the way WordPress includes the plugin file when it calls the activation hook.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download