2013-06-05 44 views
-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-標籤」,但它不因爲沒有我的變量($路徑和$ defaultPath)是呼應的工作。 我無法找到我的錯誤,你能幫助我嗎?...問候

+0

不要'回聲',而是'返回'字符串。 –

回答

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,而不是使你的代碼按預期方式工作。

+0

謝謝:)偉大的作品 –

相關問題