Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Lazy initialization
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===PHP=== Here is an example of lazy initialization in [[PHP]] 7.4: <syntaxhighlight lang="php"> <?php header('Content-Type: text/plain; charset=utf-8'); class Fruit { private string $type; private static array $types = array(); private function __construct(string $type) { $this->type = $type; } public static function getFruit(string $type) { // Lazy initialization takes place here if (!isset(self::$types[$type])) { self::$types[$type] = new Fruit($type); } return self::$types[$type]; } public static function printCurrentTypes(): void { echo 'Number of instances made: ' . count(self::$types) . "\n"; foreach (array_keys(self::$types) as $key) { echo "$key\n"; } echo "\n"; } } Fruit::getFruit('Apple'); Fruit::printCurrentTypes(); Fruit::getFruit('Banana'); Fruit::printCurrentTypes(); Fruit::getFruit('Apple'); Fruit::printCurrentTypes(); /* OUTPUT: Number of instances made: 1 Apple Number of instances made: 2 Apple Banana Number of instances made: 2 Apple Banana */ </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)