调用PHP函数时不会执行

Hus*_*ain 1 php function

我遇到了这个功能的问题.它应该回应一些东西,但由于某种原因,当我打电话时它不会这样做.

这是功能:

$count = count($info['level']);
function displayInfo()
{
  for ($i=0; $i<$count; $i++)
  {
    echo "[b]".$info['name'][$i]."[/b]\n\n"
    ."Level: ".$info['level'][$i]
    ."\nPrice: ".$info['price'][$i]
    ."\nSellback: ".$info['sell'][$i]
    ."\nLocation: ".$location
    ."\n\nType: ".$info['type'][$i]
    ."\nElement: ".$info['element'][$i]
    ."\nDamage: ".$info['damage'][$i]
    ."\nBTH: ".$info['bth'][$i]
    ."\n\nSPECIAL"
    ."\nHits: ".$info['hits'][$i]
    ."\nType: ".$info['stype'][$i]
    ."\nElement: ".$info['selement'][$i]
    ."\nDamage: ".$info['sdamage'][$i]
    ."\nBTH: ".$info['sbth'][$i]
    ."\nRate: ".$info['rate'][$i]
    ."\n\nDescription\n".$description
    ."\n".$img
    ."\n\n\n";
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我用来调用函数的代码:

<?PHP
    displayInfo();
?>
Run Code Online (Sandbox Code Playgroud)

我无法找出什么是错的 - 这不是一个sintax错误,页面加载没有中断.

提前致谢.

Pas*_*TIN 8

你在函数之外声明$count$info变量:

// $info already exists
$count = count($info['level']);  // and $count is initialized here
function displayInfo()
{
for ($i=0; $i<$count; $i++)
...
Run Code Online (Sandbox Code Playgroud)

在PHP中,从函数内部看不到函数外部声明的变量.


如果您希望从函数内部看到"外部"变量,则必须在函数中声明它们global:

$count = count($info['level']);
function displayInfo()
{
global $count, $info;
// $count is now visible ; same for $info
for ($i=0; $i<$count; $i++)
...
Run Code Online (Sandbox Code Playgroud)


但通常认为将变量作为参数传递给函数会更好:您必须将它们声明为参数:

function displayInfo($count, $info)
{
for ($i=0; $i<$count; $i++)
...
Run Code Online (Sandbox Code Playgroud)

并在调用它时将它们传递给函数:

$count = count(...);
displayInfo($count, $info);
Run Code Online (Sandbox Code Playgroud)

传递参数而不是使用全局变量可确保您了解您的函数可以访问和修改的内容.


编辑:谢谢你的注释,X-Istence!没有阅读足够的给定代码:-(


Tom*_*igh 5

$ count和$ info在函数外部声明,因此它们在其中不可见.您可以将$ info传递给函数,然后在其中计算$ count,如下所示:

//get info from db, or somewhere
$info = array();    

displayInfo($info);

function displayInfo($info)
{
    $count = count($info['level']);
    //now $count and $info are visible.
}
Run Code Online (Sandbox Code Playgroud)

http://php.net/manual/en/language.variables.scope.php