【问题标题】:function not included, why? [closed]功能不包括在内,为什么? [关闭]
【发布时间】:2013-06-05 21:05:00
【问题描述】:

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

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)都没有回显。 我找不到我的错误,你能帮我吗?...问候

【问题讨论】:

  • 不要echo,而是return 字符串。

标签: php function include


【解决方案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 可以让您的代码按预期工作。

【讨论】:

  • 谢谢 :) 很棒的作品
猜你喜欢
  • 2014-05-27
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
相关资源
最近更新 更多