需要php中的多态单例示例

时间:2013-12-22 05:20:00

标签: php singleton polymorphism

请给我看一下php中多态sigleton的例子。

谷歌发现很少有人提及这一点以及C中的所有内容,这对我来说并不清楚

2 个答案:

答案 0 :(得分:0)

我不清楚你的“多态单身”是什么意思。单例模式本身已在很多地方得到解释,例如:

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

在PHP中,您可以使用以下简单代码实现单例模式:

<?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

答案 1 :(得分:0)

你走了:

/**
 * 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 );
        }
    }
}