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
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:
MUST BE VALID
Solve the problem:
47 - 17 = ?
Subscribe to this entry?

 
 [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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 02:01:30 2024 UTC