如何解决PHP中缺少一个finally块? [英] How can I get around the lack of a finally block in PHP?

查看:254
本文介绍了如何解决PHP中缺少一个finally块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在5.5版之前的PHP没有最终的阻止 - 即,在大多数敏感语言中,您可以执行以下操作:

PHP prior to version 5.5 has no finally block - i.e., whereas in most sensible languages, you can do:

try {
   //do something
} catch(Exception ex) {
   //handle an error
} finally {
   //clean up after yourself
}

PHP没有一个finally块的概念。

PHP has no notion of a finally block.

任何人都有解决这个令人兴奋的漏洞的经验?

Anyone have experience of solutions to this rather irritating hole in the language?

推荐答案

解决方案,否。刺激麻烦的解决方法,是的:

Solution, no. Irritating cumbersome workaround, yes:

$stored_exc = null;
try {
    // Do stuff
} catch (Exception $exc) {
    $stored_exc = $exc;
    // Handle an error
}
// "Finally" here, clean up after yourself
if ($stored_exc) {
    throw($stored_exc);
}

Yucky,但应该工作。

Yucky, but should work.

请注意:PHP 5.5终于(ahem,sorry)添加了一个finally块: https://wiki.php.net/rfc/finally (和它只需要几年...在5.5 RC中可用的近四年来,自从我发布了这个答案... )

Please note: PHP 5.5 finally (ahem, sorry) added a finally block: https://wiki.php.net/rfc/finally (and it only took a few years... available in the 5.5 RC almost four years to the date since I posted this answer...)

这篇关于如何解决PHP中缺少一个finally块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆