Page 1 of 1

global variables

Posted: Mon Jul 03, 2006 5:40 pm
by barry_normal
Hello, I want to use a global variable instead of passing things back and forth but just declaring it seems to kill my whole show.

Take away the word global and it works up to a point... the point being where I want to access my global array.

Why is this happening to me?

Any help would be really brilliant.

Code: Select all

global $allPages = array();
$p_count = 0;
function loadFiles($fn){
for($x = 0; $x < count($fn); $x++){
$doc = domxml_new_doc("1.0");
$doc = domxml_open_file($fn[$x]);
getTitles($doc);
}
doHead("Bulletin");
outputNews($allPages);
doFoot();
}

Re: global variables

Posted: Mon Jul 03, 2006 5:58 pm
by Christopher
The global keyword is to identify variabies inside a function as global. Like this:

Code: Select all

$allPages = array();
$p_count = 0;
function loadFiles($fn){
    global $allPages;
    for($x = 0; $x < count($fn); $x++){
        $doc = domxml_new_doc("1.0");
        $doc = domxml_open_file($fn[$x]);
        getTitles($doc);
    }
    doHead("Bulletin");
    outputNews($allPages);
    doFoot();
}
Although this would be preferable:

Code: Select all

$allPages = array();
$p_count = 0;
function loadFiles($fn, $allPages){
    for($x = 0; $x < count($fn); $x++){
        $doc = domxml_new_doc("1.0");
        $doc = domxml_open_file($fn[$x]);
        getTitles($doc);
    }
    doHead("Bulletin");
    outputNews($allPages);
    doFoot();
}

Posted: Mon Jul 03, 2006 6:04 pm
by barry_normal
thanks Christopher,

Interesting. In the end I did it without globals but I'll keep this in mind for next time...

Cheers
B

Posted: Mon Jul 03, 2006 6:16 pm
by Christopher
barry_normal wrote:Interesting. In the end I did it without globals but I'll keep this in mind for next time...
Not using globals is generally considered a better practice.