Skip to content

Instantly share code, notes, and snippets.

@arnissolle
Last active November 5, 2022 05:20
Show Gist options
  • Select an option

  • Save arnissolle/507352525655a336c9e9ed04225397bb to your computer and use it in GitHub Desktop.

Select an option

Save arnissolle/507352525655a336c9e9ed04225397bb to your computer and use it in GitHub Desktop.
<?php
trait Singleton
{
private static $instance;
public static function getInstance(...$args): static
{
if (null === self::$instance) {
self::$instance = new static(...$args);
}
return self::$instance;
}
}
class Foo
{
use Singleton;
private function __construct(
private int $id
) {}
public function bar(): string
{
return "FooBar: {$this->id}";
}
}
@arnissolle
Copy link
Author

arnissolle commented Jun 15, 2022

Foo::getInstance(1)->bar(); // FooBar: 1
Foo::getInstance(2)->bar(); // FooBar: 1

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