How can I get around the lack of a finally block in PHP?

前端 未结 7 2166
不思量自难忘°
不思量自难忘° 2020-12-08 18:26

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) {
   //ha         


        
7条回答
  •  自闭症患者
    2020-12-08 18:48

    Here is my solution to the lack of finally block. It not only provides a work around for the finally block, it also extends the try/catch to catch PHP errors (and fatal errors too). My solution looks like this (PHP 5.3):

    _try(
        //some piece of code that will be our try block
        function() {
            //this code is expected to throw exception or produce php error
        },
    
        //some (optional) piece of code that will be our catch block
        function($exception) {
            //the exception will be caught here
            //php errors too will come here as ErrorException
        },
    
        //some (optional) piece of code that will be our finally block
        function() {
            //this code will execute after the catch block and even after fatal errors
        }
    );
    

    You can download the solution with documentation and examples from git hub - https://github.com/Perennials/travelsdk-core-php/tree/master/src/sys

提交回复
热议问题