Last active
April 25, 2025 06:08
-
-
Save chadyred/00c2af75f69ac793810f10227ad9c520 to your computer and use it in GitHub Desktop.
Keep instance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface F{} | |
class Article implements F | |
{ | |
public function __construct(public readonly string $foo) | |
{ | |
} | |
} | |
interface FactoryAwareInterface{ | |
public static function getInstance(string $className, ...$with): F; | |
} | |
trait ClassInstanceCached | |
{ | |
private static object $real; | |
public static function getInstance(string $className, ...$with): F | |
{ | |
return self::$real ??= (new static())->build($className, ...$with); | |
} | |
} | |
class FactoryAware implements FactoryAwareInterface | |
{ | |
use ClassInstanceCached; | |
public static function build(string $className, ...$with): F | |
{ | |
if(is_a($className, F::class, true)) { | |
return new $className(...$with); | |
} | |
throw new RuntimeError("Not a F"); | |
} | |
} | |
$a = FactoryAware::getInstance(Article::class, "foo"); | |
$sameAsA = FactoryAware::getInstance(Article::class, "foo"); | |
$sameAsABis = FactoryAware::getInstance(Article::class, "foo"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment