How to work with variable functions and callbacks

How to pass one function to another

A variable function

      $function = (mt_rand(0,1) == 1) ? 'array_sum' : 'array_product'; 
      $values = array(4, 9, 16); 
      $result = $function($values); 
      

A function that uses a callback

      function validate($data, $functions) { 
        $valid = true; 
        foreach ($functions as $function) { 
          $valid = $valid && $function($data); 
        } return $valid; 
      } 
      function is_at_least_18($number) { 
        return $number >= 18; 
      } 
      function is_less_than_62($number) { 
        return $number < 62; 
      } 
      $age = 25; 
      $functions = array('is_numeric', 'is_at_least_18', 'is_less_than_62'); 
      $is_valid_age = validate($age, $functions); // true 
      

Language constructs that can’t be used in variable functions

      die eval echo empty exit
      include include_once isset list print 
      require require_once return unset
      

Back