|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #65750 Enabling factory constructors
Submitted: 2013-09-24 08:40 UTC Modified: 2021-07-23 09:31 UTC
From: thomas dot sahlin at invented dot se Assigned:
Status: Wont fix Package: *General Issues
PHP Version: Irrelevant 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: thomas dot sahlin at invented dot se
New email:
PHP Version: OS:


 [2013-09-24 08:40 UTC] thomas dot sahlin at invented dot se
It would be nice to be able to create factory constructors (like Dart offers). 
This could be achieved by allowing __construct to return an arbitrary object of 
the same class or a descendant thereof.

No return statement would then mean "return $this;" as it is today.

Sure, one can use a static factory method, but it's not as elegant and cannot 
simply be added to existing code without modifying all places where objects are 

Test script:
class MyClass
  public function __construct($id)
    if (isset(self::$cache[$id]))
      return self::$cache[$id];

    // Do expensive setup

    self::$cache[$id] = $this;

  private static $cache = array();


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2021-07-23 09:31 UTC]
-Status: Open +Status: Wont fix
 [2021-07-23 09:31 UTC]
Going to explicitly decline this, we're not going to muddy constructor semantics in this fashion. Please do use a static factory method.
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Thu Aug 05 03:01:24 2021 UTC