开发者

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?

Regards, Alexander


To answer literal question:

// 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;
}

Documentation here: http://php.net/manual/en/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.


you have to do this with the global keyword

here an example

$arr = array('bar');
function foo() {
    global $arr;
    echo array_pop($arr);
}
foo();


I concur with others that this is not the preferred way to do it, and you should be passing the array as a parameter, but I just wanted to point out the $GLOBALS[] superglobal array, which I find more readable than the global keyword.

$global_array = array(1,2,3);

function myfunc()
{
  echo $GLOBALS['global_array'][0];
  print_r($GLOBALS['global_array']);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜