|   | php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
| 
  [2019-08-24 11:56 UTC] forziforzi at gmail dot com
 Description: ------------ --- From manual page: https://php.net/class.closure --- So, no Singleton in the PHP! Test script: --------------- <?php final class A { private function __construct() {} private function __clone() { throw new \Exception('Singleton'); } private function __sleep() { throw new \Exception('Singleton'); } private function __wakeup() { throw new \Exception('Singleton'); } public static function instantiate() { static $obj; return $obj = $obj ?? new self; } } $closure = function () { $class = get_class($this); return new $class; }; $obj = A::instantiate(); var_dump($obj); var_dump($closure->call($obj)); PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             | |||||||||||||||||||||||||||
|  Copyright © 2001-2025 The PHP Group All rights reserved. | Last updated: Fri Oct 31 09:00:01 2025 UTC | 
If you really care, you can do this; <?php final class A { static $obj; private function __construct() { if (isset(self::$obj)) { throw new \Exception('Singleton'); } self::$obj = $this; } private function __clone() { throw new \Exception('Singleton'); } private function __sleep() { throw new \Exception('Singleton'); } private function __wakeup() { throw new \Exception('Singleton'); } public static function instantiate() { return self::$obj ?? new self; } }