2009-08-06 71 views
0

如何构成PHP函数失败的if/else语句?如果它有效,我希望它以单向方式定义$results,如果不适用,则需要另一个方向。我不想简单地显示错误,或者如果错误消息失败,请将它们杀死。如何处理PHP函数错误?

目前,我有:

if(file_get_contents("http://www.address.com")){ 
    $results = "it worked";} 
else { 
    $results = "it didnt";} 
return $results 

回答

1
if(@file_get_contents("http://www.address.com");){ 
    $results = "it worked";} 
else { 
    $results = "it didnt";} 
return $results 

前面加一个@的功能,可以surpress它的错误消息。

2

你想PHP的try/catch functions

它会是这样的:

try { 
    // your functions 
} 
catch (Exception e){ 
    //fail gracefully 
} 
+1

我认为try/catch只能在PHP5中使用,并且抛出抛出异常。不知道虽然... – fresskoma

+0

x3ro是正确的,恐怕try/catch只适用于仅由PHP的新的OO风格功能(如PDO)抛出的异常。因此,如果文件不存在,那么不会像file_get_contents()那样产生警告错误。 但是,您可以从任何地方抛出异常,并且我认为可以通过ErrorException类将异常致命错误发送到异常。见http://www.php.net/manual/en/language.exceptions.php和http://www.php.net/manual/en/class.errorexception.php。 – simonrjones

0

正如传染性说的那样,如果函数抛出一个异常,try/catch函数就可以正常工作。但是,我认为你正在寻找的是一种处理函数结果的好方法,它返回你的预期结果,而不一定会抛出异常。我不认为file_get_contents会抛出异常,而只是返回false。

你的代码可以正常工作,但我注意到一个额外的;在if语句的第一行。

if (file_get_contents("http://www.address.com")) { 
    $results = "it worked"; 
} else { 
    $results = "it didnt"; 
} 
return $results; 

此外,您可以将函数调用的结果存储到变量中,以便稍后使用它。

$result = file_get_contents("http://www.address.com"); 
if ($result) { 
    // parse your results using $result 
} else { 
    // the url content could not be fetched, fail gracefully 
}