I have a requirement ("config.php") with arrays, but still get the variable Undefined

I have a function that looks something like this:

require("config.php"); function displayGta() { (... lots of code...) $car = $car_park[3]; } 

and config.php, which look something like this:

 <?php $car_park = array ("Mercedes 540 K.", "Chevrolet Coupe.", "Chrysler Imperial.", "Ford Model T.", "Hudson Super.", "Packard Sedan.", "Pontiac Landau.", "Duryea."); (...) ?> 

Why can I get Note: Undefined variable: car_park ?

+7
variables php global-variables require configuration
source share
3 answers

Try to add

  global $car_park; 

in your function. When you include the definition of $ car_park, it creates a global variable and accesses it from within the function, you must declare it global, or access it through the GLOBALS superclass.

See the man page for the variable area for more information.

+14
source share

Although Paul describes what is happening, I will try to explain again.

When you create a variable, it belongs to a specific area. A region is a region in which a variable can be used.

For example, if I did this

 $some_var = 1; function some_fun() { echo $some_var; } 

a variable is not allowed inside a function because it was not created inside a function. For it to work inside the function, you must use the global keyword, so the example below will work

 $some_var = 1; function some_fun() { global $some_var; //Call the variable into the function scope! echo $some_var; } 

It is the other way around, so you cannot do the following

 function init() { $some_var = true; } init(); if($some_var) // this is not defined. { } 

There are several ways to do this, but the simplest of them is to use the $GLOBALS array, which is allowed anywhere in the script, as it is special variables.

So,

 $GLOBALS['config'] = array( 'Some Car' => 22 ); function do_something() { echo $GLOBALS['config']['some Car']; //works } 

Also, make sure your server has global registration registers disabled in your INI for security. http://www.php.net/manual/en/security.globals.php

+10
source share

You can try to proxy it in your function, for example:

function foo ($ bar) {

(the code)

$ car = $ bar [3];

(the code)

}

Then when you call it:

echo foo ($ bar);

+1
source share

All Articles