代码之家  ›  专栏  ›  技术社区  ›  ganjan

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

  •  7
  • ganjan  · 技术社区  · 15 年前

    我有一个这样的函数:

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

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

    为什么我得到 注意:未定义的变量:停车场 ?

    3 回复  |  直到 15 年前
        1
  •  14
  •   Paul Dixon    15 年前

    尝试添加

     global $car_park;
    

    manual page on variable scope 更多信息。

        2
  •  10
  •   Dennis Williamson    15 年前

    尽管保罗描述了发生的事情,我还是会再解释一遍。

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

    例如,如果我要这样做

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

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

    反之亦然,因此您不能执行以下操作

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

    有几种方法可以解决这个问题,但最简单的方法是使用 $GLOBALS

    所以

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

    另外,为了安全起见,请确保您的服务器在ini中关闭了register globals。 http://www.php.net/manual/en/security.globals.php

        3
  •  1
  •   misterte    15 年前

    您可以尝试将其代理到您的函数中,例如:

    function foo($bar){

    (代码)

    $Car=$bar〔3〕;

    (代码)

    }

    Then when you call it:

    回声FO($bar);