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
https://forums.phpfreaks.com/topic/200928-function-globals-are-dirty/
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? 

@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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.