If you’ve ever worked with WordPress’s “template tag” functions, you may have noticed that some of them take arguments in a strange way. Instead of passing arguments like function($1, $2)
, they are handled much a URL query string, like function('exclude=this&order=asc')
. This enables you to pick and choose what arguments you want to specify, and the order in which you do so.
How is that done? I wondered about that myself for quite some time, but was too lazy to open the source code and see for myself. Recently I came across the PHP function that makes it possible: Parse_Str().
Take this code snippet for example:
$str = "book=Going+Postal&author=Terry+Pratchett&type=hardcover";
parse_str($str);
echo $book . "<br />";
echo $author . "<br />";
echo $type . "<br />";
It’s not too hard to figure out what the script would output. The first line returned would be “Going Postal,” the second “Terry Pratchett,” and the third “hardcover.” Perhaps $str
could be passed to a function, in some script involving books, that would often have differing amounts of arguments passed. (WordPress’s template tags are really the best example I can think of.)
Obviously there are many applications for this, not just passing data between functions, such as when dealing with JavaScript or some advanced query string trickery. I’m sure you’ll find a use for it eventually…