开发者

php functions - doesn't work

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?


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.


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜