Skip to content

Instantly share code, notes, and snippets.

@mikoj
Last active May 12, 2022 14:33
Show Gist options
  • Save mikoj/e95cc1200c9c5c5bf3707e282314cde3 to your computer and use it in GitHub Desktop.
Save mikoj/e95cc1200c9c5c5bf3707e282314cde3 to your computer and use it in GitHub Desktop.
php7 Singleton final private __construct
<?php
interface ISingleton {
public static function getInstance(): ISingleton;
}
abstract class Singleton implements ISingleton {
private static $_instances = [];
final private function __construct () {}
final private function __clone() {}
final private function __wakeup() {}
final public static function getInstance() : ISingleton {
self::$_instances[static::class] = self::$_instances[static::class] ?? new static();
return self::$_instances[static::class];
}
}
class Person extends Singleton {
public $age = 0;
}
class Man extends Person {
}
class Woman extends Person {
}
$person1 = Person::getInstance();
$person1->age = 1;
$man1 = Man::getInstance();
$man1->age = 2;
$woman1 = Woman::getInstance();
$woman1->age = 3;
var_dump($person1, $man1, $woman1, Person::getInstance(), Man::getInstance(), Woman::getInstance());
@thefrosty
Copy link

If you're going the PHP 7 route, you can change $className to static::class and remove get_called_class().

@mikoj
Copy link
Author

mikoj commented Aug 3, 2018

@Tony-Sol
Copy link

Some warnings will be here if you're using php 8.0 and above:

Warning: Private methods cannot be final as they are never overridden by other classes in /home/user/scripts/code.php on line 11
Warning: Private methods cannot be final as they are never overridden by other classes in /home/user/scripts/code.php on line 12
Warning: The magic method Singleton::__wakeup() must have public visibility in /home/user/scripts/code.php on line 12

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment