views:

56

answers:

3

Hi. I hava a function that looks something like this:

require("config.php");

function displayGta()
{
    (... lots of code...)

    $car = $car_park[3]; 
} 

and a config.php that 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 do I get Notice: Undefined variable: car_park ?

+10  A: 

Try adding

 global $car_park;

in your function. When you include the definition of $car_park, it is creating a global variable, and to access that from within a function, you must declare it as global, or access it through the $GLOBALS superglobal.

See the manual page on variable scope for more information.

Paul Dixon
great. That fixed the problem :D
ganjan
Alternately you could `require()` the file from inside of the function itself. That'd also put it in the correct scope. I can't say I'd actually recommend doing that, but the point is: when you include a file, it's run in the scope the include statement is in.
Frank Farmer
+4  A: 

Even though Paul describes what's going on I'll try to explain again.

When you create a variable it belongs to a particular scope. A scope is an area where a variable can be used.

For instance if I was to do this

$some_var = 1;

function some_fun()
{
   echo $some_var;
}

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

$some_var = 1;

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

This is vice versa so you can't do the following

function init()
{
   $some_var = true;
}

init();

if($some_var) // this is not defined.
{

}

There are a few ways around this but the simplest one of all is using $GLOBALS array which is allowed anywhere within the script as they're special variables.

So

$GLOBALS['config'] = array(
   'Some Car' => 22
);

function do_something()
{
   echo $GLOBALS['config']['some Car']; //works
}

Also make sure your server has Register globals turned off in your INI for security. http://www.php.net/manual/en/security.globals.php

RobertPitt
+1  A: 

You could try to proxy it into your function, like:

function foo($bar){

(code)

$car = $bar[3];

(code)

}

Then when you call it:

echo foo($bar);

misterte