[wp-hackers] odd behaviour vs. global variables

Ozh ozh at planetozh.com
Fri Jun 13 14:19:00 GMT 2008


>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!

Totally normal and expected given your snippet.

dosomething() runs with a variable given by the add_action, which content 
goes into $do_comment. But then on first line of the function you're 
telling it: don't care about what you've been sent in, use the global 
variable instead! Which is probably empty since you probably didn't 
declare it anywhere.

In other words:

$do_comment = 'hello';
function dosomething($do_comment) {
    global $do_comment; 
    print_r($do_comment);
    return $do_comment;
}
add_action('preprocess_comment', 'dosomething');

This will always return 'hello', no matter what's actually sent into 
dosomething().

Suggestion: read again some PHP docs about variable scope :)

Ozh





More information about the wp-hackers mailing list