Skip to content

Instantly share code, notes, and snippets.

@Xeoncross Xeoncross/Lazy.php forked from meglio/Lazy.php
Created Jan 30, 2014

Embed
What would you like to do?
<?php
/**
* Trait Lazy
*
* Allows for lazy initialization of object and class values.
*
* Example:
*
* class Test {
* use Lazy;
*
* // The name of the functions, i.e. 'x' and 'y', will be used as a key for the storage of initialized values
*
* function x() { return $this->lazy( function(){ return 'heavy-computation'; } ); }
*
* static function y() { return self::lazyStatic( function(){ return 'heavy-computation'; } ); }
* }
*/
trait Lazy
{
private $__lazilyInitialized = [];
private static $__lazilyInitializedStatic = [];
private static function __initializeLazily(&$storage, callable $initializer)
{
$key = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function'];
if (!array_key_exists($key, $storage))
{
if (is_callable($initializer))
$storage[$key] = call_user_func($initializer);
else
throw new RuntimeException('$initializer is not callable');
}
return $storage[$key];
}
/**
* @param callback $initializer
* @return mixed
*/
protected function lazy(callable $initializer)
{
return self::__initializeLazily($this->__lazilyInitialized, $initializer);
}
/**
* @param $initializer
* @return mixed
*/
protected static function lazyStatic(callable $initializer)
{
return self::__initializeLazily(self::$__lazilyInitializedStatic, $initializer);
}
}
@Xeoncross

This comment has been minimized.

Copy link
Owner Author

Xeoncross commented Jan 30, 2014

Run the function when needed and then store the result so the closure is not called a second time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.