开发者

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

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 ?


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.


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


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);


I had the same issue and have been tearing my hair out over it - nothing worked, absolutely nothing - until in desperation I just copied the contents of config.php into a new file and saved it as config2.php (without changing anything in its contents at all), changed the require_once('config.php'); to require_once('config2.php'); and it just started working.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜