So I\'m programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I
When you will need a function in the future which performs a task that you have decided upon now.
For example, if you read a config file and one of the parameters tells you that the hash_method
for your algorithm is multiply
rather than square
, you can create a closure that will be used wherever you need to hash something.
The closure can be created in (for example) config_parser()
; it creates a function called do_hash_method()
using variables local to config_parser()
(from the config file). Whenever do_hash_method()
is called, it has access to variables in the local scope ofconfig_parser()
even though it's not being called in that scope.
A hopefully good hypothetical example:
function config_parser()
{
// Do some code here
// $hash_method is in config_parser() local scope
$hash_method = 'multiply';
if ($hashing_enabled)
{
function do_hash_method($var)
{
// $hash_method is from the parent's local scope
if ($hash_method == 'multiply')
return $var * $var;
else
return $var ^ $var;
}
}
}
function hashme($val)
{
// do_hash_method still knows about $hash_method
// even though it's not in the local scope anymore
$val = do_hash_method($val)
}