global variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
barry_normal
Forum Newbie
Posts: 21
Joined: Sun Jul 02, 2006 5:02 am

global variables

Post 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();
}
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: global variables

Post 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();
}
(#10850)
barry_normal
Forum Newbie
Posts: 21
Joined: Sun Jul 02, 2006 5:02 am

Post 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
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post 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.
(#10850)
Post Reply