Re: Why is variable not in scope?

From: Date: Sun, 28 Jul 2019 03:47:09 +0000
Subject: Re: Why is variable not in scope?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-326870@lists.php.net to get a copy of this message
Functions don't automatically have access to global variables. Use the 'global' keyword to declare what global variables you're going to use in your function. function nav_list() { global $auth_array; // Code... } https://www.php.net/manual/en/language.variables.scope.php On Sat, Jul 27, 2019, 19:47 John <john.iliffe@iliffe.ca> wrote: > There is probably another way to do this but I have spent a good few hours > trying to resolve it and I think there is something wrong with the way I > understand the scope of variables in PHP, so an answer would be > appreciated. > > I have a PHP (7.1.3) programme that opens a database during initialization, > gathers an associative array of variables (pg_fetch_array) and then closes > the > database. The array name is $auth_array. During actual display of the > page the > values of the elements of the array are used to control what is (not) > displayed > and lookup of the values is done using a separate function. > > At this point I can print_r() the array and it contains what I expect. > > In the next line, I call a user-defined function nav_list() where this > array is > used in the form $auth_array['column name']. At this point I get a PHP > error > "Got error 'PHP message: PHP Notice: Undefined variable: auth_array in > /httpd/myprogramme/yrarcex.php on line 74\nPHP message: PHP Notice: > Undefined > variable: auth_array .... . At this point I cannot print_r the array, the > same > undefined variable message appears. > > I expected that auth_array would be in global scope. > > so I tried calling nav_list() with no arguments, then with the name of the > array > as the only argument, and with the address of the array (&$auth_array) and > also > with the explicit cast nav_list(array $auth_array) and I always get the > same > error message. (not a data type error as suggested in the docs). > > So far as I can see I am following the online documentation at > > https://www.php.net/manual/en/functions.arguments.php > > exactly. > > The definition of nav_list() is; > > function nav_list() > { > if ($auth_array['u_....'] == 't') <---- this is line 74 as shown in > the > error > { > // display something > } > } > > >

« previous php.general (#326870) next »