design-patterns/code/singleton.php
2025-07-03 19:35:54 +03:00

49 lines
1.2 KiB
PHP

<?php
/**
* @package: patterns
* @author: Yevhen Odynets
* @date: 2025-07-03
* @time: 08:39
*/
declare(strict_types = 1);
use Pattern\Creational\{Singleton\Single, Singleton\Singleton};
/**
* The client code.
*
* @noinspection ForgottenDebugOutputInspection
*/
function clientCode(): void
{
$output = [
'where' => trace(),
's1' => Singleton::getInstance('s1'),
's2' => Singleton::getInstance('s2'),
];
if ($output['s1'] === $output['s2']) {
$output['message'] = "Singleton works, both variables contain the same instance.";
} else {
$output['message'] = "Singleton failed, variables contain different instances.";
}
$output['s1']->setValue('value set from s1@Singleton::class');
dump($output['s1']->getValue());
$output['s2']->setValue('value set from s2@Singleton::class');
dump($output, $output['s1']->getValue(), $output['s2']->getValue());
}
clientCode();
$single = Single::getInstance('from subclass');
$single->setValue('value set from Single::class')->childish();
$singleton = Singleton::getInstance('from Singleton');
/** @noinspection ForgottenDebugOutputInspection */
dump($single->getValue(), $singleton->getValue());