tags:

views:

39

answers:

0

Here's the code I have. Everything works fine except when trying to use the same declared class variable in script more than once with a function.

include("include/database.class.php");
$db = new Database();
$db->connect();
function fill_roles()
{

    global $db;
    $r = $db->get_roles_all_order_by_name();
    $drop_down = "<select id='dd_roles' name='dd_roles'>
                <option>&nbsp;</option>";
    while($row = mysql_fetch_array($r))
    {
        $drop_down .= "<option value=$row[id]>$row[role_display_name]</option>";
    }
    $drop_down .= "</select>";
    return $drop_down;
}
//$test = mysql_num_rows($db->get_users_with_role_all());
echo $test . fill_roles();

If I leave the code as written above, the drop down box is filled in. As soon as I uncomment this line

//$test = mysql_num_rows($db->get_users_with_role_all());

the drop down box is no longer filled in.

If I change the top of the fill_roles() function to this

function fill_roles()
{

        //global $db;
        $db = new Database();
        $db->connect();

        ...rest of code as above...

}

It all works again.

For some reason using "global $db" doesn't work when I've used a method of $db, then call the function fill_roles(). For some reason I have to re-declare the class Database inside the function even though I have it as "global $db;"

I know "global $db;" is working fine because of the little comment I made for "//$test = ...", when it's no longer calling a method of Database before going to the function fill_roles().

With my beginner's knowledge of PHP I'm looking at it and thinking it should work but for some reason it's being anal. How can I avoid having to re-declare the class Database in the function and also not have to pass in the variable $db in to fill_roles() to avoid re-declaration.