|  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: -
From: thomas dot sahlin at invented dot se Assigned:
Status: Open Package: *General Issues
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [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

PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Mon Mar 08 22:01:23 2021 UTC