|  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: 2019-07-19 18:03 UTC
From: php-bugs at allenjb dot me dot uk Assigned:
Status: Open Package: Class/Object related
PHP Version: Next major version OS:
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
Block user comment
Status: Assign to:
Bug Type:
From: php-bugs at allenjb dot me dot uk
New email:
PHP Version: OS:


 [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.
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Wed Sep 30 16:01:24 2020 UTC