【问题标题】:My PHP Function isn't working我的 PHP 函数不工作
【发布时间】:2009-10-12 16:24:27
【问题描述】:

以下代码有问题。它应该做的是回显cats.php,后跟example.php,但它不回显example.php。任何想法为什么会发生这种情况?

$bookLocations = array(
    'example.php',
    'cats.php',
    'dogs.php',
    'fires.php',
    'monkeys.php',
    'birds.php',
);

echo $bookLocations[1];

function findfile($filenumber)
{
echo $bookLocations["$filenumber"];
}

findfile(0);

【问题讨论】:

  • 我不明白为什么有人会否决这个问题。

标签: php user-defined-functions


【解决方案1】:

尝试改变,

echo $bookLocations["$filenumber"];

到:

echo $bookLocations[$filenumber];

编辑* 要扩展 Thomas 的正确答案,您可以将方法更改为:

function findfile($filenumber, $bookLocations)
{
    echo $bookLocations[$filenumber];
}

【讨论】:

  • 确实如此。 “托马斯”在下面有正确的答案。您需要使用全局 $foo;在你的职能范围内。这是一个范围界定问题。
  • 最好尝试echo $bookLocations;
  • @genio:这是个坏建议,全局变量是邪恶的!
  • 嘿,不知道我怎么忽略了这一点。应该可能只是更改为将数组作为参数传递,然后以这种方式使用它。
  • +1 因为这个答案明显优于当前接受的答案stackoverflow.com/questions/1555521/…
【解决方案2】:

我相信您可能还需要在函数中声明全局变量。

global $bookLocations;

【讨论】:

  • 不同意你的观点,但鉴于提供的功能,这是唯一的方法。更改函数声明的一些建议也相当有效。
  • 那是另一个问题,tharkun。他本可以在回答中提到这一点,但这显然是全科医生试图做的,所以这是正确的答案。
  • 不,这不是正确的答案!这是错误的答案!正确答案是将数组传递给函数!
  • 你真的不应该接受这个答案,因为你会帮助推广不良做法!一般来说,使用全局变量是一种不好的做法!
  • 哈哈,塔昆,冷静点。 :) 让他以艰难的方式学习它。 :P
【解决方案3】:

好的,有两个问题。

变量范围

你的函数不知道数组$bookLocations,你需要像这样将它传递给你的函数:

function findfile($filenumber, $bookLocations)

数组键

您不想将数组键括在引号中:

wrong: $bookLocations["$filenumber"];
right: $bookLocations[$filenumber];

【讨论】:

  • 因为数组键是 $filenumber 而不是 $filenumber 括在引号中。它不是字符串,而是整数。
  • 这取决于 PHP 配置。不过最好避免使用括号。
【解决方案4】:

当数组的键都是数字时,"$filenumber" 中的引号将您的键转换为字符串。您正在尝试访问$bookLocations["1"],而实际上您想要访问$bookLocations[1]——也就是说,1"1"相同.因此,正如其他人所说,您需要去掉键周围的引号(并检查您的变量范围)。

【讨论】:

    【解决方案5】:
    function findfile($filenumber)
    {
      global $bookLocations;
      echo $bookLocations[$filenumber];
    }
    

    优秀的开发人员通常会避免使用全局变量。相反,将数组作为参数传递给函数:

    function findfile($files, $filenum)
    {
      echo $files[$filenum];
    }
    

    【讨论】:

      【解决方案6】:

      $bookLocations 超出了您的功能范围。如果您回显 $filenumber,您将看到它在范围内,因为您按值传递了它。但是,没有引用 $bookoLocations。

      你应该传入 $bookLocations

      声明:函数 findfile($filenumber, $bookLocations){ 调用:findfile(1, $bookLocations);

      您也可以将 $bookLocations 声明为全局变量,但应尽可能避免使用全局变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-23
        • 2018-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多