What is the best way of reading parameters in functions?

LaftLeacy

New Member
I've created several helper functions which I use when creating templates for Wordpress.An example is this:\[code\]function the_related_image_scaled($w="150", $h="150", $cropratio="1:1", $alt="", $key="related" )\[/code\]The problem is, if I only want to pass along the \[code\]$alt\[/code\] parameter, I also have to populate \[code\]$w\[/code\], \[code\]$h\[/code\] and \[code\]$cropratio\[/code\].In one of my plugins, I use the following code:\[code\]function shortcode_display_event($attr) { extract(shortcode_atts(array( 'type' => 'simple', 'parent_id' => '', 'category' => 'Default', 'count' => '10', 'link' => '' ), $attr)); $ec->displayCalendarList($data); }\[/code\]This allows me to call the function only using e.g.\[code\]count=30\[/code\].How can I achieve the same thing in my own functions?SOLUTION
Thanks to my name brother (steven_desu), I have come up with a solution that works.I added a extra function (which I found on the net) to create value - pair from a string.The code looks as follows:\[code\]// This turns the string 'intro=mini, read_more=false' into a value - pair arrayfunction pairstr2Arr ($str, $separator='=', $delim=',') { $elems = explode($delim, $str); foreach( $elems as $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 will no longer contain'main' but will contain 'mini' echo $intro;}some_name('intro=mini, read_more=false')\[/code\]Info
With good feedback from Pekka, I googled and found some info regarding the Named Arguments and why it's not in PHP: http://www.seoegghead.com/software/php-parameter-skipping-and-named-parameters.seo
 
Back
Top