2011-07-05 117 views
1

我想检查IF中三个函数中的任何一个是否没有成功执行。如果他们中的任何一个没有运行,我想要返回值为false。关于PHP函数返回的问题

if($ext == "gif" or $ext == "png"){ 
    imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127)); 
    imagealphablending($new, false); 
    imagesavealpha($new, true); 
    } 

例如,我想知道是否所有的三个功能了imagecolortransparent,imagealphablending,imagesavealpha没有成功执行,如果没有,返回false。 我需要检查每个功能,如下或有更好的方法

if($ext == "gif" or $ext == "png"){ 
    if ([email protected]($new, imagecolorallocatealpha($new, 0, 0, 0, 127))) 
     return false; 
    if ([email protected]($new, false)) 
     return false; 
    if ([email protected]($new, true)) 
     return false; 
} 

谢谢。

+0

什么是__better__? – gnur

+0

我只是想知道如果我需要为每个函数返回false,因为在我的图像调整大小函数im使用许多内置的图像相关函数,所以我必须单独返回每个函数返回值。 – sunjie

回答

0

如果一个函数调用失败,您可以将它们加入到1个单元中,但是您的方法可能是更好的方法,因为它不会执行以下语句。

+2

布尔'&&'操作符也会短路,遇到'false'时停止执行。 – deceze

0

您可以设置一个自定义错误处理程序,将所有PHP错误转换为ErrorException s并在全局范围内进行注册。一旦你这样做了,三个函数中任何一个的错误都会引发一个异常,你可以使用try/catch块来处理异常。

0
if ([email protected]($new, imagecolorallocatealpha($new, 0, 0, 0, 127)) 
    || [email protected]($new, false) 
    || [email protected]($new, true)) return false; 

或只是

return (@imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127)) 
    && @imagealphablending($new, false) 
    && @imagesavealpha($new, true)); 

不知道,如果@这里需要。你应该尽量避免它。

0

我认为你所做的相当好,但可以连接表达式。这是做同样的,并且如果一个函数返回false,表达不会遵循其余的(运行时优化):使用一个变量,爱惜第二

if($ext == "gif" or $ext == "png"){ 
    if (
     @imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127)) 
     and @imagealphablending($new, false) 
     and @imagesavealpha($new, true) 
    ) return true; 
    return false; 
} 

或者 如果从而使它更表情:

if($ext == "gif" or $ext == "png") 
    return 
     @imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127)) 
     && @imagealphablending($new, false) 
     && @imagesavealpha($new, true) 
    ; 
0

以下是我该怎么做。

if($ext == "gif" or $ext == "png"){ 
    $return = TRUE; 
    $return = $return && imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127)); 
    $return = $return && imagealphablending($new, false); 
    $return = $return && imagesavealpha($new, true); 
    return $return; 
} 

基本上我And -ing所有响应,以确认它们都是真实的。如果其中任何一个返回FALSE,该功能将返回FALSE

有更多美丽的方式来做到这一点,但我发现这种方式可以合理清楚到底发生了什么。

+0

请问为什么downvote?我总是乐于接受建设性的批评。 – Icode4food