PHP函数变量范围 [英] php function variable scope
问题描述
我想知道我是否具有这样的功能:
I was wondering if i have a function like this:
function isAdmin ($user_id) {
$admin_arr = array(1, 2);
foreach ($admin_arr as $value) {
if ($value == $user_id) {
return true;
}
}
return false;
}
我是否可以在该函数外部创建一个数组作为全局数组,并在函数内部使用它而不将其作为参数发送,还可以像我上面所做的那样在函数内部声明一个新的管理数组?我该怎么办?
Could i make an array outside of that function as a global array and use it inside the function without sending it through as a parameter, also instead declaring a new admin array inside the function as i just did above? How would i do this?
关于, 亚历山大
推荐答案
要回答字面问题:
// Global variable
$admin_arr = array(1, 2);
function isAdmin ($user_id) {
// Declare global
global $admin_arr;
foreach ($admin_arr as $value) {
if ($value == $user_id) {
return true;
}
}
return false;
}
此处的文档: http://php.net/manual/zh/language .variables.scope.php
要回答真实的问题:不惜一切代价避免全球化.您正在向应用程序中引入大量容易出错的代码.依靠全局变量进入了一个痛苦的世界,这使您的功能不再那么有用.
To answer the REAL question: Avoid global at all costs. You are introducing a plethora of error prone code into your application. Relying on global variables is entering a world of pain and makes your functions less useful.
除非绝对没有其他方法,否则请避免.
Avoid it unless you absolutely see no other way.
这篇关于PHP函数变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!