PHP 8.5.0 Alpha 1 available for testing

Voting

: max(one, nine)?
(Example: nine)

The Note You're Voting On

davidsch
4 years ago
There are discussions below regarding how to create a singleton that allows subclassing. It seems with get_called_class there is now a cleaner solution than what is discussed below, that does not require overriding a method per subclass.

e.g.

<?php
abstract class MySuperclass {
static private
$instances = array();

static public function
getInstance(): ACFBlock {
$className = get_called_class();
if (!isset(
self::$instances[$className])) {
self::$instances[$className] = new static();
}
return
self::$instances[$className];
}

private function
__construct() {
// Singleton
}
}

class
MySubclass extends MySuperclass {
}

MySubclass::getInstance();

<< Back to user notes page

To Top