Closures in PHP… what, precisely, are they and when would you need to use them?

前端 未结 8 1351
囚心锁ツ
囚心锁ツ 2021-01-29 20:50

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

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-29 21:23

    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)
    }
    

提交回复
热议问题