2009-11-04 76 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"; 
?>