|  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
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please — but make sure to vote on the bug!
Your email address:
Solve the problem:
31 + 34 = ?
Subscribe to this entry?

 [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: Sun Sep 19 12:03:36 2021 UTC