调用PHP函数时不会执行

时间:2009-12-04 19:44:35

标签: 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";
  }
}

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

<?PHP
    displayInfo();
?>

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

提前致谢。

5 个答案:

答案 0 :(得分:8)

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

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

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


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

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


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

function displayInfo($count, $info)
{
for ($i=0; $i<$count; $i++)
...

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

$count = count(...);
displayInfo($count, $info);

传递参数而不是使用全局变量可确保您知道您的函数可以访问的内容 - 并进行修改。


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

答案 1 :(得分: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.
}

请参阅http://php.net/manual/en/language.variables.scope.php

答案 2 :(得分:3)

为应该从函数访问的变量添加global,但不是参数:

function displayInfo()
{
     ## bad design
     global $count, $info;
     ...

或者将数组作为参数传递:

function displayInfo($info)
{
    ## this is local variable accessable only inside function
    $count = count($info['level']);
    ...
}

致电

<?php
    ## don't forget to pass array as parameter
    displayInfo($info);
?>

答案 3 :(得分:1)

您可以在函数内移动$ count,也可以将其传递给函数。此外,您的$ info数组也必须传递给函数,或者是全局的。这是函数原型,其中count和info被传递给函数。

function displayInfo($count, $info)
{

    for ($i=0; $i<$count; $i++)
    {
    // Do stuff
    }
}

<?php
    $count = count($info['level']);
    displayInfo($count, $info);
?>

答案 4 :(得分:0)

确实,没有语法错误,但还有其他错误,正如其他反应所指出的那样。我强烈建议您在编写新代码时配置PHP以显示所有错误。这样你就会看到关于$ info和$ count的通知没有在你的函数中定义。

您可以通过多种方式打开错误。

  1. 配置您的服务器以执行此操作。
  2. 使用.htaccess文件打开它们
  3. 在脚本的最开头使用以下PHP代码。
  4. 示例:

    error_reporting(E_ALL | E_NOTICE); //turn on all errors
    ini_set("display_errors","On"); //activate display_error
    
相关问题