My stream of consciousness being a programmer.

Sunday, April 8, 2012

PHP has no FINALLY

Image result for php 5.3
I am so curious why PHP doesn’t have FINALLY block along with normal TRY CATCH blocks. It’s very much necessary and will let us stay away from code duplication. Finally is simply to do something at last after try catch block. Even if there is an exception finally will be called at last.

 class A  
 {  
   public function doSomething()  
   {  
   }  
 }  
 ...  
 ....  
 try {  
 $a->doSomething();  
 $b->status = 'success';  
 }  
 catch(exception $ex) {  
 $ex->getMessage();  
 $b->status = 'fail';  
 }  
 finally {  
 $b->save();  
 }  

Since we don’t have finally right now in php 5.4 we have to re write the above code section as following which is bit of over load work.

 try {  
 $a->doSomething();  
 $b->status = 'success';  
 $b->save();  
 }  
 catch(exception $ex) {  
 $ex->getMessage();  
 $b->status = 'fail';  
 $b->save();  
 }  

You can see i am writing the save method at two places thinking if an exception occurs. So if we have finally we may not need it this way. However as the php.net site says, Finally block has been approved now and will be pushed out with php 5.5 soon. it’s a good news and we got to stay for latest php version badly.

Popular Posts

Powered by Blogger.