php - What is the best way of reading parameters in functions? -
i've created several helper functions use when creating templates wordpress. example this:
function the_related_image_scaled($w="150", $h="150", $cropratio="1:1", $alt="", $key="related" )   the problem is, if want pass along $alt parameter, have populate $w, $h , $cropratio.
in 1 of plugins, use following code:
function shortcode_display_event($attr) {      extract(shortcode_atts(array(         'type' => 'simple',         'parent_id' => '',         'category' => 'default',         'count' => '10',         'link' => ''     ), $attr));    $ec->displaycalendarlist($data);  }   this allows me call function using e.g.count=30.
how can achieve same thing in own functions?
solution
 name brother (steven_desu), have come solution works.
i added function (which found on net) create value - pair string.
the code looks follows:
// turns string 'intro=mini, read_more=false' value - pair array function pairstr2arr ($str, $separator='=', $delim=',') {     $elems = explode($delim, $str);     foreach( $elems $elem => $val ) {         $val = trim($val);         $nameval[] = explode($separator, $val);         $arr[trim(strtolower($nameval[$elem][0]))] = trim($nameval[$elem][1]);     }         return $arr; }  function some_name($attr) {   $attr = pairstr2arr($attr);    $result = array_merge(array(         'intro' => 'main',         'num_words' => '20',         'read_more' => 'true',         'link_text' => __('read more')     ), $attr);    extract($result);    // $intro no longer contain'main' contain 'mini'   echo $intro; }  some_name('intro=mini, read_more=false')   info
 feedback pekka, googled , found info regarding named arguments , why it's not in php: http://www.seoegghead.com/software/php-parameter-skipping-and-named-parameters.seo
i suggest using array_merge() , extract() @ beginning of function, passing parameters arrays if possibility.
function whatever($new_values){     $result = array_merge(array(         "var1" => "value1",         "var2" => "value2",         "var3" => "value3"     ), $new_values);     extract($result);      echo "$var1, $var2, $var3"; }  whatever(array("var2"=>"new_value"));   the above output:
value1, new_value, value3   it's bit sloppy , uses more memory since has allocate arrays, it's less efficient solution. allow avoid redundancy. i'm sure better method exists using magic meta-code, can't think of off-hand.
Comments
Post a Comment