Пример #1
0
 /**
  * Test the getInstance method
  */
 public function testSingleton()
 {
     $a1 = A::getInstance();
     $a2 = A::getInstance();
     $this->assertEquals($a1, $a2);
     $b = B::getInstance();
     $this->assertNotEquals($a1, $b);
 }
Пример #2
0
<?php

trait Singleton
{
    protected static $_instance = null;
    public static function getInstance()
    {
        if (static::$_instance === null || !static::$_instance instanceof static) {
            static::$_instance = new static();
        }
        return static::$_instance;
    }
}
class A
{
    use Singleton;
    private function __construct()
    {
    }
}
$a = A::getInstance();
var_dump($a instanceof A);
var_dump($a instanceof Singleton);
var_dump(is_a($a, 'Singleton'));
function main()
{
    // the interpreter should correctly go to A::foo
    A::getInstance()->foo();
}