Viewed   140 times

Possible Duplicate:
Who needs singletons?

I always write with respect to best practice, but I also want to understand why a given thing is a best practice.

I've read on in an article (I unfortunately don't remember) that singleton classes are prefered to be instantiated, rather than being made with static functions and accessed with the scope resolution operator (::). So if I have a class that contains all my tools to validate, in short:

class validate {
    private function __construct(){}
    public static function email($input){
        return true;

I've been told this is considered bad practice (or at least warned against), because of such things as the garbage collector and maintenance. So what the critiques of the "singleton class as static methods" wants, is that I instantiate a class I'm 100% certain I will only ever instantiate once. To me it seems like doing "double work", because it's all ready there. What am I missing?

What's the view on the matter? Of course it's not a life and death issue, but one might as well do a thing the right way, if the option is there :)



An example singleton classes in php:
Creating the Singleton design pattern in PHP5 : Ans 1 :
Creating the Singleton design pattern in PHP5 : Ans 2 :

Singleton is considered "bad practice".

Mainly because of this: How is testing the registry pattern or singleton hard in PHP?

  • why are singleton bad?

  • why singletons are evil?

  • A good approach: Dependency Injection

  • Presentation on reusability: Decouple your PHP code for reusability

  • Do you need a dependency injection container

  • Static methods vs singletons choose neither

  • The Clean Code Talks - "Global State and Singletons"

  • Inversion of Control Containers and the Dependency Injection pattern

Wanna

  • What are the disadvantages of using a PHP database class as a singleton?

  • Database abstraction class design using PHP PDO

  • Would singleton be a good design pattern for a microblogging site?

  • Modifying a class to encapsulate instead of inherit

  • How to access an object from another class?

  • Testing Code That Uses Singletons

A Singleton decision diagram (source):

Saturday, October 8, 2022

The short answer is no.

Each page request is handled as a unique instance and the only thing that tie them together for each user is the session cookie. Try to think of PHP as an application which starts when you call a script and dies when the script finishes. It does not maintain any state and is not inherently aware of any other PHP instances.

The singleton pattern is simply a way for you to design a class, where you can call it anywhere in your code (like a global) without having to care about whether it already has been instantiated or not and you want it to persist in memory.

Friday, September 23, 2022

Inheriting Singleton class in PHP is difficult, event in PHP 7.0, but you can do this with some changes on your class to work.

first make your Singleton class to abstract

abstract class Singleton {


change your $instance variable to array $instance(s)

private $instances = [];

Now change getInstance() method like below

public static function getInstance() {
  if (!isset(self::$instances[static::class]) {
    self::$instances[static::class] = new static();

  return self::$instances[static::class];

And change your test

remember now you can't call Singleton:: getInstance() due to abstract

class SingletonChild extends Singleton {

class SingletonChildTwo extends SingletonChild {

$obj = SingletonChild::getInstance();
$obj_two = SingletonChildTwo::getInstance();
var_dump($obj === SingletonChild::getInstance()); // true
var_dump($obj === $obj_two); // will -> false
Wednesday, August 10, 2022

Inner classes (static or not) have exactly the same access to their enclosing class' fields and methods as anonymous classes, the difference between static inner classes (actually called nested classes) and (regular, non-static) inner classes being that the static one need an explicit reference to an instance of the enclosing class to access something. Of course, when you need to do that, it's usually on the instance of the enclosing class that created the inner class, so it's easier and clearer to use a non-static inner class.


  • Inner class (non-static)

    class A {
        private int field;
        private class B {
            public void doSomething() {
                field++; // Valid
  • Nested class (i.e. "static inner class")

    class A {
        private int field;
        private static class B {
            public void doSomething(A a) {
                a.field++; // Valid
  • Anonymous class

    class A {
        private int field;
        public void doSomething() {
            new Runnable() {
                public void run() {
                    field++; // Valid

Whether you use that accessibility is another question. If you do access private fields of the enclosing class, there'll be an accessor generated, so it could impact the performance as the cost of calling a method is not the same as accessing a field, but it will probably be negligible in most cases. You should always write correct code first (both in terms of design and functionality) before doing micro-optimizations not based on any measurement. The JIT compiler does a lot of things for you anyway.

Wednesday, August 24, 2022

Actually, the above answer was not completely correct.

require 'singleton'

class Example
  include Singleton

You also need to include the require 'singleton' statement.

Wednesday, August 10, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :