2009-11-04 23 views

回答

4

,如果你不想與污染額外的功能和諸如此類的東西命名空間,這是一個循環do { ... } while (0);完美的情況。

do { 
    // processing 
    if (!check_file_size($image)) { 
     echo 'The image is too big'; 
     break; 
    } 

    if (!check_file_type($image)) { 
     echo 'The image is of the wrong type'; 
     break; 
    } 

    echo $image; 
} while (0); 

的DO-而(0)循環正從某種加工條件退出,而無需編寫一個函數,函數調用到你的代碼的無名英雄。雖然收益可以忽略不計,但這也會阻止PHP解析器不得不創建額外的符號,然後再次查找它,原因很少。

編輯:它也可以防止你進入巨大的if塊金字塔,當你的條件變得太大。如果你把它包裝在一個if塊中,並且每個後續的條件在一個依賴的if塊中,你最終會有這個巨大的,難以遵循的縮進混亂(假設你設置了你的代碼的格式),用很難追蹤的閉合括號到他們的開幕式;使用do { ... } while (0);將所有內容保持在相同的邏輯縮進級別。

+0

感謝您的信息。我接受了這個建議,但是感謝大家的意見。總是喜歡學習新的東西。 – mrpatg 2009-11-04 12:18:51

+0

+1,我喜歡這個'絕招'。以前從來沒有見過它,所以感謝教給我一些新的東西。 :P – Duroth 2009-11-04 12:27:34

+0

+1,可能派上用場。如果您正在查找更詳細的錯誤消息(即* filesize太大* **和** *無效擴展名*),那麼也可以將它與@ RM的解決方案混合以便連接錯誤消息。 – 2009-11-05 13:45:48

6

你應該把你的代碼移入一個函數,然後你可以從它return

function processImage($img) 
{ 
    if (imageIsTooLarge($img)) 
     return false; 

    doOtherStuff(); 
    return true; 
} 

$ok = processImage($someImage); 
1

你可以,純樸的緣故,包裹在如果()語句的代碼。

// continue parsing image if filesize not greater than maxsize 
if ($filesize <= $max_size) { 

    // contine parsing image if filetype is fine 
    if (in_array($extension, array('jpg','jpeg','gif')) { 

     // remainder of your PHP code goes in here for parsing image upload 

    } 
} 

所有的HTML都應該低於這個PHP塊。

1

退出你字面意思是退出()?如果是這樣,請考慮爲用戶生成錯誤消息並顯示該消息,您可以放棄上傳的文件。

if(image is too large) { 
    $err = "The image you uploaded is too large"; 
} 

if(image wrong file type) { 
    $err = "You have not uploaded a valid image file"; 
} 

if(!isset($err) { 
    proceesImage(); 
} 

// echo out $err to user 
0

使用新轉到功能:

<?php 
//code is executed 
goto a; 
//code is not executed 
echo "Not Executed"; 

a: 
//code is executed 
echo "Executed"; 
?>