php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #46286 Extending class with static getInstance()-type method
Submitted: 2008-10-13 18:14 UTC Modified: 2008-10-13 18:39 UTC
From: bob at db dot org Assigned:
Status: Not a bug Package: Feature/Change Request
PHP Version: 5.3.0alpha2 OS: Any
Private report: No CVE-ID: None
 [2008-10-13 18:14 UTC] bob at db dot org
Description:
------------
A getInstance() method is a fairly common design-pattern, yet it's impossible to create such a function in a base-class and have it function as expected when access via the inheriting class.

I understand that this is documented behavior, and that it's probably impossible to achieve this using existing syntax/functions. What I'm hoping for is a new function; something like get_statis_class(void) that will return the name of the class used to *access* the static method, not the name of the class in which it was defined.

I can provide more elaboration on why this is a nice feature if needed. The attached example is kept short to illustrate the problem as clearly as possible.

Reproduce code:
---------------
<?php

class base {
        public static function getInstance() {
                $class = __CLASS__;
                return new $class();
        }
}

class heir extends base {
}

$instance = heir::getInstance();

die(get_class($instance));

?>

Expected result:
----------------
heir

Actual result:
--------------
base

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-10-13 18:38 UTC] colder@php.net
Sorry, but your problem does not imply a bug in PHP itself.  For a
list of more appropriate places to ask for help using PHP, please
visit http://www.php.net/support.php as this bug system is not the
appropriate forum for asking support questions.  Due to the volume
of reports we can not explain in detail here why your report is not
a bug.  The support channels will be able to provide an explanation
for you.

Thank you for your interest in PHP.

retrurn new static();
 [2008-10-13 18:39 UTC] colder@php.net
return new static();
or $name = get_called_class(); new $name();

Read on php.net/oop5.late-static-bindings for more details
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Jun 02 02:01:29 2024 UTC