-2

我的代码有什么问题???:

function my_function()
{
$states = array('schwarz', 'rot', 'blau');

$path = '';

foreach ($states as $state) {
    $testPath = sprintf('transactions/Ordner/%s.png', $state);

    if (file_exists($testPath)) {
      $path = $testPath;
      echo $path;
    }
    else {
      $defaultPath = "inventory_images/8.jpg";
      echo $defaultPath;
    }
}
}


$imagesPerLine = array(1=>2, 2=>3); $default = 4;
$lines = array(1, 2, 3);
$html="";
foreach ($lines as $line) {
if (!isset($imagesPerLine[$line])) {
  $imagesPerLine[$line] = $default;
}
$html.= "<tr>\n";
for ($i = 1; $i <= $imagesPerLine[$line]; $i++) {
  $html.=sprintf("<td>%s</td>\n", my_function());
}
$html.="</tr>\n";

}
echo $html;  

我想,我将 my_function() 包含在“td-tag”中,但它不起作用,因为我的变量($path 和 $defaultPath)都没有被回显。我找不到我的错误,你能帮我吗?...问候

4

1 回答 1

1

你应该return代替echo.

为简化起见,让我们将代码更改为:

$text = my_function();
$html = sprintf("<td>%s</td>\n",$text);

出于所有实际目的,这与您的原始代码相同。

您的my_function()电话包含echo陈述。这些被评估并发送输出。该函数本身没有return语句,因此您的代码实际上变为:

echo "something";
$text = null;
$html = sprintf("<td>%s</td>",$text);

相反,使用return会使您的代码按预期工作。

于 2013-06-05T21:09:01.963 回答