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

前端 未结 8 1428
囚心锁ツ
囚心锁ツ 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:38

    I like the context provided by troelskn's post. When I want to do something like Dan Udey's example in PHP, i use the OO Strategy Pattern. In my opinion, this is much better than introducing a new global function whose behavior is determined at runtime.

    http://en.wikipedia.org/wiki/Strategy_pattern

    You can also call functions and methods using a variable holding the method name in PHP, which is great. so another take on Dan's example would be something like this:

    class ConfigurableEncoder{
            private $algorithm = 'multiply';  //default is multiply
    
            public function encode($x){
                    return call_user_func(array($this,$this->algorithm),$x);
            }
    
            public function multiply($x){
                    return $x * 5;
            }
    
            public function add($x){
                    return $x + 5;
            }
    
            public function setAlgorithm($algName){
                    switch(strtolower($algName)){
                            case 'add':
                                    $this->algorithm = 'add';
                                    break;
                            case 'multiply':        //fall through
                            default:                //default is multiply
                                    $this->algorithm = 'multiply';
                                    break;
                    }
            }
    }
    
    $raw = 5;
    $encoder = new ConfigurableEncoder();                           // set to multiply
    echo "raw: $raw\n";                                             // 5
    echo "multiply: " . $encoder->encode($raw) . "\n";              // 25
    $encoder->setAlgorithm('add');
    echo "add: " . $encoder->encode($raw) . "\n";                   // 10
    

    of course, if you want it to be available everywhere, you could just make everything static...

提交回复
热议问题