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

前端 未结 7 2188
不思量自难忘°
不思量自难忘° 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:53

    function _try(callable $try, callable $catch, callable $finally = null)
    {
        if (is_null($finally))
        {
            $finally = $catch;
            $catch = null;
        }
    
        try
        {
            $return = $try();
        }
        catch (Exception $rethrow)
        {
            if (isset($catch))
            {
                try
                {
                    $catch($rethrow);
                    $rethrow = null;
                }
                catch (Exception $rethrow) { }
            }
        }
    
        $finally();
    
        if (isset($rethrow))
        {
            throw $rethrow;
        }
        return $return;
    }
    

    Call using closures. Second parameter, $catch, is optional. Examples:

    _try(function ()
    {
        // try
    }, function ($ex)
    {
        // catch ($ex)
    }, function ()
    {
        // finally
    });
    
    _try(function ()
    {
        // try
    }, function ()
    {
        // finally
    });
    

    Properly handles exceptions everywhere:

    • $try: Exception will be passed to $catch. $catch will run first, then $finally. If there is no $catch, exception will be rethrown after running $finally.
    • $catch: $finally will execute immediately. Exception will be rethrown after $finally completes.
    • $finally: Exception will break down the call stack unimpeded. Any other exceptions scheduled for rethrow will be discarded.
    • None: Return value from $try will be returned.

提交回复
热议问题