简体   繁体   English

Try/Catch 块中的 PHP 变量范围

[英]PHP variable scope within Try/Catch block

In PHP, how do variable scope rules apply to Try/Catch blocks?在 PHP 中,变量范围规则如何应用于 Try/Catch 块? Do variables declared within the try block go out of scope when the block has finished?当块完成时,在try块中声明的变量是否超出范围? Or are they in scope until the end of the function/method?或者它们是否在函数/方法结束之前的范围内?

For example:例如:

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

$o->doPronk();

Is this valid?这是有效的吗? Or should $o = NULL;或者应该$o = NULL; be set before the try/catch to keep $o in scope?在 try/catch 之前设置以保持$o在范围内?

(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 在范围界定方面可能会变得有点愚蠢。我的问题是,理想情况下,它应该如何工作?正确和正确的方法是什么?)

Your code is valid. 您的代码有效。 Variable scope in PHP is by function, not block. PHP中的变量范围是按功能而不是阻止。 So you can assign a variable inside the try block, and access it outside, so long as they're in the same function. 所以你可以在try块中分配一个变量,并在外面访问它,只要它们在同一个函数中。

I believe this is opinion based mostly. 我认为这主要是基于意见的。 The code is correct and it will work as expected as long as the catch block always has the return statement. 代码是正确的,只要catch块始终具有return语句,它将按预期工作。 if the catch block does not return, the flow will continue and the code outside the try/catch block will be executed, and it will fail, because $o won't be initialized. 如果catch块没有返回,则流程将继续,并且try / catch块外部的代码将被执行,并且它将失败,因为$o将不会被初始化。 You will be able to access $o because of the lack of block scope in php, but the method won't exist because the object construction failed. 您将能够访问$o因为php中缺少块范围,但该方法将不存在,因为对象构造失败。

the main concept for the exception handling is that if anything goes wrong inside the "try" block the code will enter into the "catch" block. 异常处理的主要概念是,如果“try”块内部出现任何问题,代码将进入“catch”块。 so if 因此,如果

$o = new Pronk();

does not raise any error it will be in scope. 不会引起任何错误,它将在范围内。 we don't have to declare it before try/catch block. 我们不必在try / catch块之前声明它。 your code is perfectly valid. 你的代码完全有效。

As long as your obj is correctly constructed you can expect to use obj outside of try/catch block只要您的 obj 构造正确,您就可以期望在 try/catch 块之外使用obj

However, suppose that there was an exception during construction.但是,假设在构建过程中出现异常。 Then your obj wouldn't be even constructed inside try block.那么你的obj甚至不会在 try 块内构建。 Therefore, you wouldn't be able to call the functions on obj because obj was not even created.因此,您将无法调用obj上的函数,因为obj甚至没有被创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM