tags:

views:

36

answers:

2

Hi! I guess I have a little understanding about functions and how they work.. Idea is to get "user's group" from database, but I don't want to write the code evey time when I need it so I decided to put it in function.

function get_role()
{
 $user_id = $_SESSION['login_ok'];
 $res = mysql_query('SELECT role FROM users WHERE id = "'.$user_id.'"') or mysql_error();
 $row = mysql_fetch_array($res);
 $role = $row['role'];
}

and then when I need it

get_role();

What I need is $role variable which I will use in if() to grant access to smth. But when I do so, it shows that $role is Undefined variable (when I do that checking with if).

Sorry for probably dumb questions but what am I doing wrong?

+1  A: 

You're forgetting to return from the function:

return $row['role'];

Functions in PHP (and a lot of other languages) start their own scope - that means that variables declared inside only exist inside the function, not outside. The only way to communicate with the "outside world" without globals is via arguments and return values.

Note that you no longer need $role = $row['role'];.

In order to get your value now, use:

$role = get_role();
Tim Čas
Thank you for the answer!
arturs
+3  A: 

Add return $role; to the end of your function.

You then can do $role = get_role(); where you call the function.

The reason your code is not working is called variable scope. The $role variable you are creating is only available within the function.

By adding the code above, you return the value of $role from your function and assign it to a local variable where you called the function.

You could also declare $role as global which will make it available everywhere, but this is considered a very bad practice.

Alan Geleynse
Yes, that scope thing... Finally I got it. Thanks!
arturs