2009-10-31 85 views
0

如何將下面的代碼中的php函數轉換爲非函數。如何將PHP函數轉換爲非函數?

<?php 
require_once ('./mysqli_connect.php'); // Connect to the db. 

function make_list ($parent) 
{ 
    global $tasks; 
    echo '<ol>'; 
    foreach ($parent as $task_id => $todo) 
    { 
     echo "<li>$todo"; 
     if (isset($tasks[$task_id])) 
     { 
      make_list($tasks[$task_id]); 
     } 
     echo '</li>'; 
    } 

    // Close the ordered list: 
    echo '</ol>'; 
} 

$mysqli = new mysqli("localhost", "root", "", "sitename"); 
$dbc = mysqli_query($mysqli,"SELECT task_id, parent_id, task FROM tasks WHERE date_completed='0000-00-00 00:00:00' ORDER BY parent_id, date_added ASC"); 

if (!$dbc) 
{ 
    // There was an error...do something about it here... 
    print mysqli_error(); 
} 
$tasks = array(); 

while (list($task_id, $parent_id, $task) = mysqli_fetch_array($dbc, MYSQLI_NUM)) 
{ 
    // Add to the array: 
    $tasks[$parent_id][$task_id] = $task; 
} 

make_list($tasks[0]); 

mysqli_close(); // close the connection 

// Include the html footer 
include('./includes/footer.html'); 
?> 

即使我沒有發佈的代碼的其餘部分是非函數形式,最好還是留下這樣的代碼。

+9

我認爲更好的問題是:爲什麼你會想要* *把你的函數成非功能? – hbw 2009-10-31 18:46:07

回答

8

第一個:您不能以簡單的方式將遞歸函數轉換爲意大利麪條代碼。
第二個:沒有必要這樣做。把你的邏輯,行爲分解爲功能,以及數據的邏輯和表達。不要用html標籤將您的代碼垃圾郵件。使用某種模板機制。

1

除了erenon的回答(這我完全支持,他已經作出,爲什麼你的問題是導致了錯誤的方向上分):

使用(或創建)一個隱藏連接一些數據庫抽象類,查詢執行等等,使得以後更改數據庫或適應接口更改變得更加容易,並且您有一個集中處理錯誤的地方。

和不說話的數據庫作爲超級用戶..