PHP 5.3.0 and the “global” keyword

This had me stumped for a while – using some 3rd party code with PHP 5.3.0, the “global” keyword didn’t seem to work any more (references to the supposedly “global” variable from within functions always gave NULL)..

You have to declare the variable as “global” before setting it in the outer scope – then it works again.

So, this used to work (but doesn’t under PHP 5.3.0) :

$util = new Utility();
global $util;
function show() {
    global $util;
    echo "$util->version";
}
but if you swap the lines of the declaration of $utils, then it does work under PHP 5.3.0 :
global $util;
$util = new Utility();
function show() {
    global $util;
    echo "$util->version";
}

6 thoughts on “PHP 5.3.0 and the “global” keyword

  1. aryan

    May 26, 2011 at 8:46pm

    man off course global still works on php 5.3.
    at least it works on 5.3.5
    cheers

  2. Mark

    February 25, 2012 at 9:05pm

    thanks! i was wondering why it didn’t seem to work any more!

  3. Actron

    September 13, 2012 at 2:36pm

    Thumbs up!

  4. Steff

    December 11, 2012 at 11:12am

    Thanks a lot! This saved me from a lot of dispair!

  5. Taffman

    April 5, 2013 at 3:26pm

    How about if the variable is set in a function

    function processFile ($file, $count)

    $count is incremented in the function when each record is added to a table, however I cant access this variable outside the function, it’s driving me mad!

Leave a Reply

Your email will not be published. Name and Email fields are required.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>