Declaring Global Variables in Function

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
neridaj
Forum Commoner
Posts: 40
Joined: Fri Jan 05, 2007 9:55 pm

Declaring Global Variables in Function

Post by neridaj »

Hi,

I'm trying to understand why declaring a variable global within a function is not working. I have a function that displays a table of users and is supposed to set a global variable to true when called in order to let another function know whether or not to display a hyperlink. Here is what I have:

Code: Select all

 
function display_users($user_array)
{
  // display the table of users
 
  // set global variable, so we can test later if this is on the page
  global $user_table;
  $user_table = true;
?>
  <br />
  <form name='user_table' action='delete_users.php' method='post'>
  <table width=300 cellpadding=2 cellspacing=0>
  <?php
  $color = "#000000";
  echo "<tr bgcolor='$color'><td><strong>User</strong></td>";
  echo "<td><strong>Delete?</strong></td></tr>";
  if (is_array($user_array) && count($user_array)>0)
  {
    foreach ($user_array as $user)
    {
      if ($color == "#cccccc")
        $color = "#ffffff";
      else
        $color = "#cccccc";
      // remember to call htmlspecialchars() when we are displaying user data
      echo "<tr bgcolor='$color'><td><a href=\"$user\">".htmlspecialchars($user)."</a></td>";
      echo "<td><input type='checkbox' name=\"del_me[]\"
             value=\"$user\"></td>";
      echo "</tr>"; 
    }
  }
  else
    echo "<tr><td>No users on record</td></tr>";
?>
  </table> 
  </form>
<?php
}
 
function display_admin_menu()
{
?>
<a href="admin_member.php">Home</a> &nbsp;|&nbsp;
<?php
  // only offer the delete option if user table is on this page
  global $user_table;
  if($user_table==true)
    echo "<a href='#' onClick='user_table.submit();'>Delete User</a>&nbsp;|&nbsp;"; 
  else
    echo "<font color='#cccccc'>Delete User</font>&nbsp;|&nbsp;"; 
}
 
Thanks for any help,

Jason
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Declaring Global Variables in Function

Post by Christopher »

You need to declare it global in the second function too. Also, it is a better practice to pass the values in and return them, or use classes to associate data with a set of functions.
(#10850)
Post Reply