Skip to content

Instantly share code, notes, and snippets.

@kanian
Last active March 2, 2019 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanian/b3d57d951bc4a7643acc2e642a2cafd5 to your computer and use it in GitHub Desktop.
Save kanian/b3d57d951bc4a7643acc2e642a2cafd5 to your computer and use it in GitHub Desktop.
<?php
class ClassThatMarksDateOfInstantiation
{
private $dob;
public function __construct()
{
$this->dob = new \DateTimeImmutable;
}
public function getDob()
{
return $this->dob;
}
}
$factoryOfDobClass = function () {
return new ClassThatMarksDateOfInstantiation;
};
$DobSingleton = singletonize($factoryOfDobClass); // -> anonymous class
$dob = new $DobSingleton; // -> new instance of anonymous class
$dob2 = new $DobSingleton; // -> same instance of anonymous class
print_r($dob->getDob() === $dob2->getDob()); // -> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment