0

如何形成if/elsePHP 函数失败的语句?我希望它定义$results一种方式,如果它有效,另一种方式,如果它不有效。我不想简单地显示错误或在失败时终止错误消息。

目前,我有:

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

3 回答 3

2

你想要 PHP 的try/catch 函数

它类似于:

try {
    // your functions
}
catch (Exception e){
    //fail gracefully
}
于 2009-08-06T20:20:43.553 回答
1
if(@file_get_contents("http://www.address.com");){
    $results = "成功了";}
别的 {
    $results = "它没有";}
返回$结果

通过在函数前面加上 @,您可以隐藏它的错误消息。

于 2009-08-06T20:21:47.090 回答
0

正如 contagious 所说,如果函数抛出异常,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
}
于 2009-08-06T20:34:27.610 回答