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

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

    Here are examples for closures in php

    // Author: HishamDalal@gamil.com
    // Publish on: 2017-08-28
    
    class users
    {
        private $users = null;
        private $i = 5;
    
        function __construct(){
            // Get users from database
            $this->users = array('a', 'b', 'c', 'd', 'e', 'f');
        }
    
        function displayUsers($callback){
            for($n=0; $n<=$this->i; $n++){
                echo  $callback($this->users[$n], $n);
            }
        }
    
        function showUsers($callback){
            return $callback($this->users);
    
        }
    
        function getUserByID($id, $callback){
            $user = isset($this->users[$id]) ? $this->users[$id] : null;
            return $callback($user);
        }
    
    }
    
    $u = new users();
    
    $u->displayUsers(function($username, $userID){
        echo "$userID -> $username
    "; }); $u->showUsers(function($users){ foreach($users as $user){ echo strtoupper($user).' '; } }); $x = $u->getUserByID(2, function($user){ return "

    $user

    "; }); echo ($x);

    Output:

    0 -> a
    1 -> b
    2 -> c
    3 -> d
    4 -> e
    5 -> f
    
    A B C D E F 
    
    c
    

提交回复
热议问题