简体   繁体   English

PHP函数-不起作用

[英]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. 我需要的是$ role变量,我将在if()中使用该变量来授予对smth的访问权限。 But when I do so, it shows that $role is Undefined variable (when I do that checking with if). 但是,当我这样做时,它表明$ role是未定义的变量 (当我使用if进行检查时)。

Sorry for probably dumb questions but what am I doing wrong? 抱歉,您可能会提出愚蠢的问题,但我做错了什么?

Add return $role; 添加return $role; to the end of your function. 到您的功能结束。

You then can do $role = get_role(); 然后,您可以执行$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. 您正在创建的$ role变量仅在该函数内可用。

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. 通过添加上面的代码,您可以从函数中返回$role的值,并将其分配给调用该函数的局部变量。

You could also declare $role as global which will make it available everywhere, but this is considered a very bad practice. 您也可以将$role声明为global ,以使其在任何地方都可以使用,但这被认为是非常不好的做法。

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. PHP(以及许多其他语言)中的函数开始其自己的作用域-这意味着在内部声明的变量仅存在于函数内部,而不存在于外部。 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']; 注意,您不再需要$role = $row['role']; .

In order to get your value now, use: 为了立即获得价值,请使用:

$role = get_role();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM