Support for callbacks on default in ake()
So ake() is designed to be incredibly efficient. However it currently has one draw back when it comes to defaults.
Take this code:
$var = ake($array, 'array.key.name', new Object());
When this is executed, a new instance of Object
will be instantiated every time regardless of whether the $default
value is actually used. This can chew up resources and potentially cause undesired code to be executed. Because of this, it has always been recommended to never use ake()
in this way. Instead, you would allow ake() to return null, test for that condition and then instantiate your object.
HOWEVER!
I had an idea to use callbacks as the default value. That would mean that we could hold off executing the code that instantiates the Object
until it is actually needed. This would be a simple change internally to ake()
that just when it comes time to use the default, we check if it is a closure
and if so, use the returned value as the default.
As such we should be able to do this:
$var = ake($array, 'array.key.name', function(){
return new Object();
});
Doing it this way means the code inside the closure only gets executed when it's needed. We could also use this to stuff the new value into the calling array like this:
$array = []
$var = ake($array, 'array.key.name', function($key) use($array){
return $array[$key] = new Object();
});
Great success!