php.net |  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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
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
Description:
------------
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 
instantiated.

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();
}


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-07-23 09:31 UTC] nikic@php.net
-Status: Open +Status: Wont fix
 [2021-07-23 09:31 UTC] nikic@php.net
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-2025 The PHP Group
All rights reserved.
Last updated: Fri May 02 01:01:29 2025 UTC