简体   繁体   English

定义这些变量的更简单方法?

[英]An easier way to define these variables?

$access_community = 1;
$access_content = 1;
$access_tools = 1;
$access_administrator = 0;
$access_moderator = 0;

Just wondering if there's an easier way to write this using an array? 只是想知道是否有更简单的方法来使用数组编写此代码? This seems like overkill. 这似乎太过分了。

Thanks! 谢谢!

You could either do something like (sucks for readability): 您可以执行以下操作(出于可读性):

$access_community = $access_content = $access_tools = 1;
$access_administrator = $access_moderator = 0;

Or as already been said, using an array: 或如前所述,使用数组:

$access = array('community' => 1,
                'content' => 1,
                'tools' => 1,
                'administrator' => 0,
                'moderator' => 0);

If you had more variables, then something like: 如果您有更多的变量,则类似于:

$access = array( 'community' => 1, 'content' => 1, ... );
foreach ($access as $k => $v) {
    $real_name = 'access_' . $k;
    $$real_name = $v;
}

Might work, but it's not that nice, and probably even more overkill than your code is now. 可能会工作,但是效果不是很好,并且可能比现在的代码更加矫kill过正。 I think that what you have isn't too bad, to be honest! 老实说,我认为您所拥有的还不错!

If you're interested, this uses indirect references or "variable variables" to actually define new variables. 如果您有兴趣,可以使用间接引用或“变量”来实际定义新变量。 I'm not too sure about scope here, however. 但是,我不太确定这里的范围。

Of course, if you can, try and just use the array directly, rather than relying on the variables being there - arrays can be changed and passed around, unlike variables. 当然,如果可以的话,请尝试直接使用数组,而不是依赖那里的变量-与变量不同,可以更改和传递数组。

Because you hardly can explain what are you doing and why, we can only guess. 因为您几乎无法解释您在做什么以及原因,所以我们只能猜测。

It looks like some ACL . 看起来像一些ACL
So, the only sensible way to set these variables is to store it in the database. 因此,设置这些变量的唯一明智的方法是将其存储在数据库中。 Especially if there will be dozens of them in the future. 尤其是如果将来会有数十种这样的产品。

http://phpgacl.sourceforge.net/ is probably what are you looking for 您可能正在寻找http://phpgacl.sourceforge.net/

So, your variables will be assigned with values from database. 因此,将为变量分配数据库中的值。

As for the answer you asked - no, there is no other way to initialize different variables with different values. 至于您要求的答案-不,没有其他方法可以用不同的值初始化不同的变量。 You have to explicitly set every variable value. 您必须显式设置每个变量值。 So, you have to define a variable name and a variable value somehow. 因此,您必须以某种方式定义变量名称和变量值。 So, 所以,

$variable = value

is the most plain and way convenient way. 是最简单,最便捷的方式。
You can make it more complicated way, but at the core it remains the same: "variable name - variable value" pairs 您可以使它变得更复杂,但是在核心方面,它仍然相同:“变量名-变量值”对

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

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