[wp-hackers] register_activation_hook() problem

Chris Jean gaarai at gaarai.com
Tue Jul 28 16:21:12 UTC 2009


In that code, I did not see a redefinition. However, if you have other
plugins, theme mods, etc that define that function, you will still have
problems. Keep in mind that redefinition isn't limited to a file, it
applies to all code that runs.

Looking at your code, it is clear that you still need to learn how
globals work. The code fatally failed because you didn't have "global
$wpdb" inside the createDatabaseTables function. Also, thumbs_install,
thumbs_init, and process_vote will not use the $thumbs global thumbs var
as you want since the global var is not localized to the functions.

Scope is really odd in PHP; frankly, I don't like how it works. So,
forget everything you knew about scope in other languages and learn how
PHP does it.

When you create a function, you create a new scope completely-unique to
that function. Nothing exists to that function except what is passed to
it as an argument or what is created inside of it. Even though a
variable may be global, it does not exist inside any function.

The way you bring a global into the function is to use the global
keyword to bring the global variable into the function's scope.

For example, doing the following will not work:

    global $var;
    $var = "Hello!\n";
    test();

    function test() {
        echo $var;
    }

The function test creates a new empty variable called $var and echoes
it's value rather than using the global. Running the code will result in
a warning: "PHP Notice:  Undefined variable: var in ..."

This is the right way to do it:

    global $var;
    $var = "Hello!\n";
    test();

    function test() {
        global $var;
        echo $var;
    }

You can read more on globals here: http://bit.ly/18fGqF

With all this said, I recommend that you avoid globals if you can.
Passing variables as arguments or storing them in objects is a
less-confusing and less bug-prone way of doing things.

Chris Jean
http://gaarai.com/
http://wp-roadmap.com/
http://dnsyogi.com/



Adam Taylor wrote:
> On Tue, Jul 28, 2009 at 4:54 PM, Chris Jean <gaarai at gaarai.com> wrote:
>
>   
>> Your error is caused by the fact that the thumbs_install function is
>> being redeclared, not by your use of the global declaration. You can
>> only define a function once, attempting to do so again will result in an
>> error.
>>
>>     
>
> I'm pretty sure I haven't defined the function more than once.. the whole
> code is here:
>
> http://pastebin.com/m1feb2d16
>
> If that helps anyone help me..
> _______________________________________________
> 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