requires polymorphic singleton example in php

10

show me please example of the polymorphic sigleton in php.

google found very few mentions about this and all in C which is not clear to me

262

Answer

Solution:

Here you go:

/**
 * Base class for Polymorphic Singleton.
 */
class Polymorphic_Singleton {

    /**
     * @var Polymorphic_Singleton 
     */
    private static $__instance = null;
    private static $__instance_class_name = "";


    /**
     * Gets an instance of Polymorphic_Singleton/
     *
     * Uses a Polymorphic Singleton design pattern. Maybe an anti-pattern. Discuss amongst yourselves.
     *
     * Can be called by a subclass, and will deliver an instance of that subclass, which most Singletons don't do.
     * You gotta love PHP.
     *
     * @return Polymorphic_Singleton 
     */
    final public static function get_instance(){
        if ( ! isset( self::$__instance ) ){
            self::$__instance_class_name = get_called_class();
            self::$__instance = new self::$__instance_class_name(); // call the constructor of the subclass
        }

        return self::$__instance;
    }

    /**
     * Don't ever call this directly. Always use Polymorphic_Singleton ::get_instance()
     *
     * @throws Exception if called directly
     */
    public function __construct(){
        if ( ! self::$__instance ){
           // do constructor stuff here...
        } else {
            throw new Exception( "Use 'Polymorphic_Singleton ::get_instance()' to get a reference to this class.", 100 );
        }
    }
}
225

Answer

Solution:

I don't clearly understand what you meant by "polymorphic singleton". The singleton pattern itself has been explained in many places out there, for instance:

http://en.wikipedia.org/wiki/Singleton_pattern

In PHP, you can achieve singleton pattern using this simple code:

<?php

class Something
{
    private static $instance;

    private function __construct() {}
    private function __clone() {}

    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}

// how to use
$instance1 = Something::getInstance();
$instance2 = Something::getInstance();
var_dump($instance1 === $instance2); // returns true proving that getInstance returns identical instance

People are also looking for solutions to the problem: php - insert reference in comment table that joins two sessions (blog and news)

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.