Try / Catch块中的PHP变量范围 [英] PHP variable scope within Try/Catch block

查看:321
本文介绍了Try / Catch块中的PHP变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,变量作用域规则如何应用于Try / Catch块? try 块中声明的变量在块完成后是否超出范围?还是它们在作用域中,直到函数/方法结束?

In PHP, how do variable scope rules apply to Try/Catch blocks? Do variables declared within the try block go out of scope when the block has finished? Or are they in scope until the end of the function/method?

例如:

try
{
   // This may throw an exception when created!
   $o = new Pronk();
}
catch (Exception $ex)
{
   // Handle & exit somehow; not important here
   return false;
}

$o->doPronk();

这有效吗?还是应该在try / catch之前设置 $ o = NULL; 来将 $ o 保留在范围内?

Is this valid? Or should $o = NULL; be set before the try/catch to keep $o in scope?

(我知道示例代码确实有效,但是我也知道PHP在范围界定时会变得有些愚蠢。我的问题是,理想情况下,应该如何工作?正确的方法是什么?)

(I know that the sample code does work, however I also know PHP can get a little stupid when it comes to scoping. My question is, ideally, how should it work? What is the correct and proper way to do this?)

推荐答案

您的验证码有效。 PHP中的变量作用域是按功能而不是块。因此,您可以在 try 块中分配一个变量,然后在外部访问它,只要它们处于同一函数中即可。

Your code is valid. Variable scope in PHP is by function, not block. So you can assign a variable inside the try block, and access it outside, so long as they're in the same function.

这篇关于Try / Catch块中的PHP变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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