Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In PHP methods, <code>self</code> always refers to the class where the method is defined. Since version 5.3.0, PHP supports “late static binding”, where you can use the <code>static</code> keyword to access overridden static methods, as well as the function <code>get_called_class()</code> to get the name of the derived class in static context.</p> <p>However, your design has a major flaw: The static property <code>$factory</code> defined in <code>Base_Factory</code> is shared across all derived classes. Therefore, the first time a singleton is created and stored in this property, all other calls to <code>getInstance()</code> will return the same object, no matter what derived class is used.</p> <p>You could use a static dictionary mapping class names to singleton objects:</p> <pre><code>abstract class Base_Factory { private static $_instances = array(); public static function getInstance() { $class = get_called_class(); if (!isset(self::$_instances[$class])) { self::$_instances[$class] = new $class(); } return self::$_instances[$class]; } } </code></pre> <p>Oh, one more thing: The fact that you are looking for a possibility to re-use code for singleton objects could be a cue to the fact that you are over-using the singleton design pattern! Ask yourself if the classes you are planning to implement as singletons really are singletons and if there will be no use case where you might want to have multiple instances of the particular class.</p> <p>Often it is much better to use just one singleton representing the current “application context” that provides accessors for objects that are singletons with respect to this context.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload