PHP相当于Ruby的救援

时间:2013-11-19 22:47:14

标签: php ruby sockets try-catch rescue

没有足够的声誉来正确标记(ruby,PHP,socket,rescue)

我很长时间没有练过PHP,因为我一直在做更多的Ruby脚本。我有点尴尬地请求帮助。

我知道,在Ruby中,我可以使用rescue来防止脚本在发生错误时崩溃,我希望用PHP实现同样的目的。

例如,在Ruby中:

require 'socket'

begin puts "Connecting to host..." 
host = TCPSocket.new("169.121.77.3", 333) 
# This will (intentionally) fail to connect, triggering the rescue clause. 
rescue puts "Something went wrong." 
# Script continues to run, allowing, for example, the user to correct the host IP. 
end

我的PHP代码有点乱 - 这已经很长时间了。

function check_alive($address,$service_port) { 
    /* Create a TCP/IP socket. */ 
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); 
    if ($socket === false) { 
      echo socket_strerror(socket_last_error());
    } 
    else { 
      echo null; 
    } 
    $result = socket_connect($socket, $address, $service_port); 
    if ($result === false) { 
       echo socket_strerror(socket_last_error($socket)); 
       return 1; 
    }
    else { 
       echo null; 
    } 
    socket_close($socket); 
    return 0; } 
    $hosts = [...]; 
    // list of hosts to check 
    foreach($hosts as $key=>$host) { 
       check_alive($hosts); 
    }

基本上,我有一系列主机,我想查看它们是否还活着。所有主机都没有必要存活,所以这就是我被困住的地方 - 数组中第一个死主机崩溃了脚本。

我们非常感谢任何建议 - 我愿意接受我不完全理解PHP中的套接字连接。

2 个答案:

答案 0 :(得分:5)

PHP等价物是:

try { ... } catch (...) { ... }

如果您使用的是PHP 5.5,那么还有:

try { ... } catch (...) { ... } finally { ... }

你可以有几个catch子句,每个子句捕获一个不同的异常类。

最终部分始终运行,包括引发异常的时间。

答案 1 :(得分:2)

以下是exception handling的等效PHP:

try { // equivalent of Ruby `begin`

} catch(Exception $e) { // equivalent of Ruby `rescue(e)`

}