gan*_*jan 7 php variables configuration global-variables require
我有一个看起来像这样的函数:
require("config.php");
function displayGta()
{
(... lots of code...)
$car = $car_park[3];
}
Run Code Online (Sandbox Code Playgroud)
和一个看起来像这样的config.php:
<?php
$car_park = array ("Mercedes 540 K.", "Chevrolet Coupe.", "Chrysler Imperial.", "Ford Model T.", "Hudson Super.", "Packard Sedan.", "Pontiac Landau.", "Duryea.");
(...)
?>
Run Code Online (Sandbox Code Playgroud)
为什么我会收到通知:未定义的变量:car_park?
Pau*_*xon 14
尝试添加
global $car_park;
Run Code Online (Sandbox Code Playgroud)
在你的功能.当你包含$ car_park的定义时,它正在创建一个全局变量,并且要从函数中访问它,你必须将它声明为全局变量,或者通过$ GLOBALS超全局访问它.
Rob*_*itt 10
尽管保罗描述了正在发生的事情,但我会再次尝试解释.
创建变量时,它属于特定范围.范围是可以使用变量的区域.
例如,如果我这样做
$some_var = 1;
function some_fun()
{
echo $some_var;
}
Run Code Online (Sandbox Code Playgroud)
函数中不允许使用该变量,因为它不是在函数内部创建的.要使它在函数内部工作,您必须使用global关键字,以便下面的示例可以工作
$some_var = 1;
function some_fun()
{
global $some_var; //Call the variable into the function scope!
echo $some_var;
}
Run Code Online (Sandbox Code Playgroud)
反之亦然,因此您无法执行以下操作
function init()
{
$some_var = true;
}
init();
if($some_var) // this is not defined.
{
}
Run Code Online (Sandbox Code Playgroud)
有几种方法可以解决这个问题,但最简单的方法是使用$GLOBALS在脚本中允许的任何数组,因为它们是特殊变量.
所以
$GLOBALS['config'] = array(
'Some Car' => 22
);
function do_something()
{
echo $GLOBALS['config']['some Car']; //works
}
Run Code Online (Sandbox Code Playgroud)
还要确保您的服务器在INI中关闭了注册全局变量以确保安全性. http://www.php.net/manual/en/security.globals.php
| 归档时间: |
|
| 查看次数: |
7609 次 |
| 最近记录: |