[wp-hackers] Re: Odd behaviour when using classes and the register_activation_hook() function

Otto otto at ottodestruct.com
Thu Dec 4 14:43:02 GMT 2008

Yeah, this is a common mistake. A lot of people assume that the plugin
main body is globally scoped when that's not *always* the case.

You can't make any assumptions about the scope of the plugin, so if
you need to use a global, always declare it.

On Wed, Dec 3, 2008 at 9:59 PM, John Blackbourn
<johnbillion+wp at gmail.com> wrote:
> Scrap that, this is a variable scope issue.
> 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.
> See @ http://wordpress.org/support/topic/201309
> On Thu, Dec 4, 2008 at 2:25 AM, John Blackbourn
> <johnbillion+wp at gmail.com> wrote:
>> I've come across this odd issue and I'm not sure if I'm doing
>> something wrong, so would appreciate any pointers.
>> I am writing a plugin which uses register_activation_hook() to call a
>> function when the plugin is activated. From within the function that
>> gets called, another function is called which is a member function of
>> a class defined in the plugin.
>> I've cut the plugin down to the very minimum needed to demonsrate the
>> code. See: http://johnblackbourn.com/temp/helloworld.phps .
>> The problem I am seeing is that when the plugin is activated, this
>> calling of the class member function is causing a fatal error.
>> "Fatal error: Cannot redeclare activatehelloworld() (previously
>> declared in [snip] )"
>> Now, if we remove the line $helloworld->hello(); then all is fine and
>> the plugin can be activated with no errors. If we instead call another
>> function here that is not a class member function, all is fine. It
>> appears that the act of calling a class member function at this point
>> is doing something strange, or more likely, is acting in a manner that
>> I don't understand.
>> It might also be worth mentioning that, oddly enough, the plugin is
>> actually activated despite this error being shown. This may be related
>> or it may be a red herring.
>> I'm stumped. I cannot see any reason why calling a class member
>> function at this point would produce this error. Anyone?
>> John.
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers

More information about the wp-hackers mailing list