简体   繁体   中英

Is it possible to imitate Javascript closures, in PHP?

I'm learning PHP now, and i wanted to see if it preserves access to variables, the same way Javascript does in "closures".

I tried this code:

  function createGreeting($lang){

   $greeting= "";
   if($lang === 'english'){
      $greeting = 'Hello';
   }elseif($lang === 'spanish'){
      $greeting = 'Holla';
  }   

  return function($name){

      return $greeting.", ".$name;
  };
}

$greetFunction = createGreeting('english');

echo $greetFunction('John');

As you can see createGreeting() accepts a language, and returns a function, that has access to the "greeting" variable, that was defined in main function. This doesn't work. I get an error, saying that greeting is not defined. In Javascript, this will of course work, thanks to closures.

What would be the conventional way to deal with this issue, in PHP? Do i have no choice, but to declare the greeting variable inside the returned function?

yes its possible with use its makes the specified variables of the outer scope available inside the closure

function createGreeting($lang){

    $greeting= "";
    if($lang === 'english'){
        $greeting = 'Hello';
    }elseif($lang === 'spanish'){
        $greeting = 'Holla';
    }   

    return function($name) use ($greeting){
        return $greeting.", ".$name;
    };
}

$greetFunction = createGreeting('english');
echo $greetFunction('John');

Rainmx93's answer is great for producing closures but let me give an object-oriented approach to this.

class Chat {

    protected $lang;

    function __construct($lang) {
        $this->lang = $lang;
    }

    function hello() {
        switch($this->lang) {
            case 'english':
                return 'Hello';
            case 'espanol':
                return 'Hola';
        }
    }

    function greet($name) {
        return $this->hello() . ', ' . $name;
    }

}

$chat = new Chat('english')
echo $chat->greet('John');

Of course, in normal practice, you wouldn't have a method named 'hello' for a single translation. You'd have translations stored in a language file, database, or array.

The real power behind this approach, besides being more readable, would be you can have a bunch of additional methods for chatting with the user beyond just a greeting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM