Skip to content

Instantly share code, notes, and snippets.

@DASPRiD
Created September 13, 2017 19:37
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 DASPRiD/3b1e92bdbd0f1fa6a9d8a6ebc7b33fbc to your computer and use it in GitHub Desktop.
Save DASPRiD/3b1e92bdbd0f1fa6a9d8a6ebc7b33fbc to your computer and use it in GitHub Desktop.
Idea for having default instances of a class available, lazy-loaded.
<?php
final class Timezone
{
private static $utc;
public static function utc() : self
{
return self::$utc ?: self::$utc = new self('utc');
}
}
// Each time you need the UTC timezone, PHP needs to make a function call.
$utc = TimeZone::utc();
final class Timezone
{
final public static utc = new Timezone('utc');
}
<?php
final class Timezone
{
public const UTC = new self('utc');
}
// The idea here is rather simple. A constant reference to an object is stored as constant.
// Anything which would be required for this is to allow "new ClassName" constructs as
// constant expression. The value, which is the reference to an object, would actually be
// constant and thus not changable.
//
// PHP wouldn't need to take any more special care about the object in question, as it is
// its own responsibility to be immutable if required. This would not only reduce the
// execution time for that case, but also reduce the amount of code (and logic) required,
// which can become quite a lot if you need multiple default instances.
//
// Since constant expressions are only evaluated once the constant is accessed for the first
// time, this would additionally benefit from automatic lazy loading.
$utc = Timezone::UTC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment