[wp-hackers] odd behaviour vs. global variables

Jennifer Hodgdon yahgrp at poplarware.com
Fri Jun 13 15:23:39 GMT 2008

You are misunderstanding how PHP works with global/local variables.

When you put
    global $var_abc;
inside of a function, that says that inside this function, when you 
type $var_abc, you are referring to the global version of $var_abc.

So your function is ignoring the passed-in local version of 
$do_comment, in favor of the global $do_comment (which presumably has 
not been defined).

Here is what you need to do to fix this (or something similar):

// this is the global variable,
// which you need to declare outside the function
$do_comment = 0;

// use a different name for your local variable argument
function dosomething($do_comment_loc) {

     global $do_comment;

     $do_comment = $do_comment_loc;

     return $do_comment_loc; // or alternatively: die();

add_action('preprocess_comment', 'dosomething');


Matthias Vandermaesen wrote:
> I was working on my plugin for Mollom (http://www.netsensei.nl/mollom) when
> I started noticing some odd behaviour when declaring certain variables
> global. For instance, If we create this simple plugin: (omitted the
> obligatory header for brevity's sake)
> function dosomething($do_comment) {
>     global $do_comment; // let's declare it global
>     print_r($do_comment);
>     return $do_comment; // or alternatively: die();
> }
> add_action('preprocess_comment', 'dosomething');
> The $do_comment variable seems to be non-existant or empty! Meaning
> everything else breaks from here on as the input got lost somewhere along
> the way. But when we remove the 'global $do_comment' line, everything works
> like a charm and $do_comment  passes the commentdata $correctly.

Jennifer Hodgdon * Poplar ProductivityWare

Drupal/WordPress Sites, Themes, Modules/Plugins
Custom Web Programming, Web Databases
PHP, Perl, MySQL, JavaScript, XML, AJAX

More information about the wp-hackers mailing list