]> Something Witty Goes Here

codedread

PHP Gotcha

April 23rd, 2005

After I wrote this entry, I knew I had forgotten one “gotcha” from my little Remote Scripting experience. I remembered it today. It involves PHP and the annoying aspect of having to declare within a function when you want to use a global variable:

$gSomeVariable = 5;
function somefunc() {
   printf(”%d”, gSomeVariable);
}

The above will not produce “5″. Without explicitly telling PHP that gSomeVariable is a global variable, it will assume it is a local variable and currently undefined.

Do you know how many time this has tripped me up? The correct PHP code is:

$gSomeVariable = 5;
function somefunc() {
   global $gSomeVariable;
   printf(”%d”, gSomeVariable);
}

For all the times I made this mistake: AAAAAARRRRRGGGGHHHH!!!!!!!

2 Responses to “PHP Gotcha”

  1. Not exactly correct - printf(”%d”, $gSomeVariable);

  2. Or why not try:

    function somefunc( $pSomeParameter) {
    printf(ā€%dā€, $pSomeParameter);
    }

    and get rid of that god-awful global variable!

Leave a Reply

This is the captcha image, please contact me if you cannot see it

codedread codedread