Jump to content

function globals are dirty?


newbtophp

Recommended Posts

I've read in several tutorials, that globals within functions are considered 'dirty' im using them within my code, and was wondering if it could be improved in a more effective way?

 

My code:

<?php
function rank($user_id){
global $rank, $level;
$ptssql = mysql_query("SELECT * FROM site_users WHERE user_id = '$user_id'");
$ptsrow = mysql_fetch_array($ptssql);

$points = $ptsrow['points'];
if ($points <= 99){
$rank = "Jr Member";
$level = 0;
}
elseif ($points >= 100 && $points <= 299){
$rank = "Member";
$level = 1;
}
}

//usage
rank(47);

?>
Your Rank: <?php echo $rank; ?>

 

All help appreciated

Link to comment
Share on other sites

point of a function is for a bit of code to be encapsulated with its own scope.  Without that, you cannot guarantee that your function will work and/or return what it is supposed to 100% of the time.  The better thing to do would be to pass those variables as arguments and return when you are done.  Also your function should also validate those vars, make sure they are what they are supposed to be.  Or pass validation off to a separate function...for example, you have that $user_id directly in a query... where is that coming from? Is it being validated somewhere else? Can the user somehow change/influence its value at some point in time before that query? 

Link to comment
Share on other sites

@CV

 

Im validating them before they are called to the function using (intval() or the int typecast along with a mysql_num_rows() to check it exists), and its only me who has the permissions to access the functions etc. - so its all prety safe. :)

 

and @Daniel

 

Cheers for the workaround.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.