Created
September 13, 2017 19:37
-
-
Save DASPRiD/3b1e92bdbd0f1fa6a9d8a6ebc7b33fbc to your computer and use it in GitHub Desktop.
Idea for having default instances of a class available, lazy-loaded.
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
<?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(); |
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
final class Timezone | |
{ | |
final public static utc = new Timezone('utc'); | |
} |
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
<?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