开发者

Pulling values from an array in separate file

开发者 https://www.devze.com 2023-01-12 20:09 出处:网络
again. Right now I\'m having issues with some pretty basic functionality in PHP. I have a web page which includes the following code:

again. Right now I'm having issues with some pretty basic functionality in PHP. I have a web page which includes the following code:

  function laserOn()
  {
    $_SESSION['laser'] = TRUE;

    $num_victims = rand(2,125);
    $vic = rand(0, count($victims) - 1);

    print $num_victims." ".$victims[$vic]." have been vaporized!<br />";
  }

and a separate file, victims.php which i have require_once'd, that contains

$victims = array(
    1 => "chickens",
    2 => "horses",
    3 => "werewolves",
    4 => "zombies",
    5 => "vampires"开发者_开发技巧,
    6 => "cows"
);

The page, though, only displays the number and the string, not the array value. WHat am I doing wrong here?


$victims does not appear to be within the scope of your function. In order to use a global variable within function scope, you need to declare it using the global keyword (see variable scope in the php.net docs).

function laserOn()
{
  global $victims;

  // ... rest of your function
}

Alternately, you could require the file that contains the array within the function, but this might not be desired (especially if the file defines functions of its own!)

0

精彩评论

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