php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #73166 Function ruturns instruction in finally
Submitted: 2016-09-25 01:15 UTC Modified: 2016-09-25 02:04 UTC
From: shoaib dot bazmi at hotmail dot co dot uk Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.6.26 OS: Windows 10
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: shoaib dot bazmi at hotmail dot co dot uk
New email:
PHP Version: OS:

 

 [2016-09-25 01:15 UTC] shoaib dot bazmi at hotmail dot co dot uk
Description:
------------
While using try catch and finally, the function returns the instruction which is mentioned in finally block. It is prohibitted in .Net, gives syntax error and logically return statement should be a syntax error if used in finally block. I wrote a function which returns and increment by 1 in argument variable and increment by 2 in finally block. Whenever i the function it returs variable incremented by 2 i.e finally block instruction.

Test script:
---------------
function incrementVar($x)
{
try{
 return ++$x;
}catch($e){}
finally{
 return $x+2;
}
}

 echo incrementVar(1);

Expected result:
----------------
2

Actual result:
--------------
3

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-09-25 02:04 UTC] requinix@php.net
-Status: Open +Status: Not a bug -Package: PHP Language Specification +Package: Scripting Engine problem
 [2016-09-25 02:04 UTC] requinix@php.net
Your code has a mistake (catch needs a class name) and your actual output is incorrect (correct output is 4).
https://3v4l.org/kkpGu

This is not a bug. Code in a finally block will always execute as soon as execution leaves the try/catch block. The function will initially try to return ++$x (2 and $x=2) but the finally will execute and it will return $x+2 (4) instead.

It's like writing
  $return = ++$x; // try { return ++$x; }
  $return = $x + 2; // finally { return $x + 2; }
  return $return;

> It is prohibitted in .Net
> return statement should be a syntax error if used in finally block
It is allowed in Java, Python, and Ruby, and they all behave the same way that PHP does.
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Wed Oct 07 23:00:01 2026 UTC