SNS - Web et informatique SNS - Web et informatique
Mercredi 4 décembre 2024 04:49 Votre adresse IP est : 18.97.14.89
Logo

PHP - Use a method as a comparison function in a class - PHP - Utiliser une méthode comme fonction de comparaison dans une classe -

Publié le .

[EN] It can be useful to use a compare function in a class in PHP. But if we follow the procedural style, we will come across a type error "cannot redeclare ..." And it makes sense. Here's how to use a class method to perform a sort function, in nested arrays, for example. [FR] Il peut être utile d'utiliser une fonction de comparaison dans une classe en PHP. Mais si on suit le style procédural, on va tomber sur une erreur du type " cannot redeclare ... " Et c'est logique. Voici comment utiliser une méthode de classe pour effectuer une fonction de tri, dans des tableaux imbriqués, par exemple.




/**
 * @version    1.0.0
 * @license    GNU GPL
 * @link       www.sns.pm
 * @author     Raphaël Castello - SNS - Web et informatique
 * // need to sort an array()
 * Function  My_Class::get_players( $ARRAY_USERS ); 
 * Function  My_Class::sort_array( $a , $b );
 */

class My_Class {


  // an array of users
  const ARRAY_USERS = array( 
      array( 'name' => 'Jamie',  'score' => 35,  'time_played' => 3600 ),
      array( 'name' => 'Abdul',  'score' => 48,  'time_played' => 10800 ),
      array( 'name' => 'Evan',  'score' => 76,  'time_played' => 14400 ),
      array( 'name' => 'Carla',  'score' => 68,  'time_played' => 7200 ),
      array( 'name' => 'Debora',  'score' => 54,  'time_played' => 1800 )
  );


/**
 * Function My_Class::sort_array( $a , $b );
 * @ access  public
 * @ static
 * @ Param. $data_type -> 'alpha' (alphabetical) / 'num' (number)
 * @ Param. $order -> 'ASC' / 'DESC'  - inverse order
 * @ Param. $key -> 'name' , 'score, etc ..
 * Sort imbricateds arrays 
 */       
  public static function sort_array( $a , $b ){
            
    $data_type = 'num' ; // 'alpha' 
    $order = 'DESC' ; // 'ASC' 
    $key = 'score'; // 'name'
            
    // SORT NUMERIC VALUES
    if( $data_type == 'num' && $order == 'DESC' ){
        return $b[$key] - $a[$key];
    }
    
    if( $data_type == 'num' && $order == 'ASC' ){
        return $a[$key] - $b[$key];
    }

    // SORT ALPHABETICAL VALUES
    if( $data_type == 'alpha' && $order == 'ASC' ){    
        return $a[$key] > $b[$key];
    }

    if( $data_type == 'alpha' && $order == 'DESC' ) {
        return $b[$key] > $a[$key];
    }
  }
/**
 * END Function My_Class::sort_array( $a , $b );
 * Sort imbricateds arrays
 */


/**
 * Function My_Class::get_players( $ARRAY_USERS );
 * @ access  public
 * @ static
 * @ Param const ARRAY_USERS  - must be an array returned by a data base
 * @ Return : all users classed
 */
  public static function get_players( $ARRAY_USERS ){
    
    // Use usort() with a public class
    usort($ARRAY_USERS, "My_Class::sort_array" );
    
    // See output in bottom  
    echo json_encode( $ARRAY_USERS , 
      JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT );
  }
/**
 * END Function lists::get_players( $ARRAY_USERS );
 *  return all users classed
 */

}
// END class My_Class


  // Launch Method 
  My_Class::get_players( My_Class::ARRAY_USERS );

  // Output : 
  [
    {
        "name": "Evan",
        "score": 76,
        "time_played": 14400
    },
    {
        "name": "Carla",
        "score": 68,
        "time_played": 7200
    },
    {
        "name": "Debora",
        "score": 54,
        "time_played": 1800
    },
    {
        "name": "Abdul",
        "score": 48,
        "time_played": 10800
    },
    {
        "name": "Jamie",
        "score": 35,
        "time_played": 3600
    }
  ]

Mots clés : utiliser une fonction de comparaison dans une classe en PHP, use a compare function in a class in PHP, PHP , compare, usort , compare in a class