当前位置: 动力学知识库 > 问答 > 编程问答 >

php - function not included, why?

问题描述:

what is wrong with my code??? :

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;

i thought, i included my_function() into the "td-tag", but it doesnt work, because none of my variables($path and $defaultPath) is echoed.

i cant find my mistake, could you help me?...greetings

网友答案:

You should return instead of echo.

To simplify, let's change your code to this:

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

This is, for all practical purposes, identical to your original code.

Your my_function() call contains echo statements. These are evaluated and the output is sent. The function itself has no return statement, therefore your code effectively becomes:

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

Using return instead makes your code work as expected.

分享给朋友:
您可能感兴趣的文章:
随机阅读: