コード例 #1
0
<?php

// Assuming every method call below returns an instance of an object, how can the following be re-written in PHP 5?
$a = new MyClass();
$b = $a->getInstance();
$c = $b->doSomething();
/*
1) $c = ((MyClass)$a->getInstance())->doSomething();
2) This cannot be re-written in PHP 5
3) $c = $a->getInstance()->doSomething();					// PHP 5+
4) $c = (MyClass)$a->getInstance();
5) $c = (new MyClass())->getInstance()->doSomething();		// PHP 5.4+  http://php.net/manual/en/migration54.new-features.php
*/
コード例 #2
0
ファイル: singleton.php プロジェクト: salebab/useful
<?php

include_once __DIR__ . "/../vendor/autoload.php";
use useful\traits\Singleton;
class MyClass
{
    use Singleton;
    public $hash;
    function __construct()
    {
        $this->hash = md5(rand());
    }
}
class MyClass2 extends MyClass
{
    use Singleton;
    // note: without defining, it will use existent instance of class MyClass
    public function getById()
    {
    }
}
echo MyClass::getInstance()->hash . PHP_EOL;
echo MyClass2::getInstance()->hash . PHP_EOL;