|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #78313 Return from constructor should trigger an error or warning
Submitted: 2019-07-19 17:24 UTC Modified: 2020-12-18 16:29 UTC
From: php-bugs at allenjb dot me dot uk Assigned: cmb (profile)
Status: Closed Package: Class/Object related
PHP Version: Next major version OS:
Private report: No CVE-ID: None
 [2019-07-19 17:24 UTC] php-bugs at allenjb dot me dot uk
It's currently possible to write a constructor that returns a value, but there is no way (as far as I can tell) to retrieve this value when constructing an object. Technically you can call the constructor directly, but this is not normally done in the course of object construction (other than calling the parent constructor).

While to experienced developers, the fact that you should/cannot return a value from a constructor seems obvious, this is not always so to newbies -

While thorough testing would obviously reveal this issue in the above case, we all know that not everyone, especially newbies, thoroughly test their code. In the above case the issue isn't obvious until an error in the curl query occurs, but all the user ends up with is an improperly constructed object - even if their code at the point of construction checks for a string value rather than an object, this check will never trigger.

Attempting to declare a return type already triggers an error:

Test script:

class Foo
    public function __construct()
        return "bar";

$foo = new Foo();

Expected result:
Error / warning that constructors cannot return a value

Actual result:
object(Foo)#1 (0) {


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2019-07-19 18:03 UTC]
-Summary: return from constructor should trigger an error or warning +Summary: Return from constructor should trigger an error or warning -Operating System: n/a +Operating System: -PHP Version: 7.3.7 +PHP Version: Next major version
 [2019-07-19 18:03 UTC]
I think there was some talk/PR to do something about calling magic methods directly which includes the constructor, destructor, __clone(), __isset() and other.

I do agree that it should do something but that would probably need an RFC from my understanding.
 [2020-12-18 16:29 UTC]
-Status: Open +Status: Closed -Assigned To: +Assigned To: cmb
 [2020-12-18 16:29 UTC]
There is a declined RFC[1] regarding enforcing void semantics.  If
you strongly feel that this decision should be reviewed, please
forward the request to the internals mailing list, and prepare to
go through the RFC process[2].

For now, you can manually declare the constructor void to catch
inadvertent returns: <>.

[1] <>
[2] <>
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Wed May 12 21:01:24 2021 UTC