views:

124

answers:

3

I happened to be making some changes to a WordPress blog and noticed that they use parse_str (http://php.net/parse_str) for parsing and setting their optional parameters to a function.

I'm wondering if there is an advantage to this over sending an array?

Examples:

With array:

$blahOptions = array(
    'option_1' => true,
);
BlahArray($blahOptions);
function BlahArray($options = array()) {
    $defaults = array(
        'option_1' => false,
        'option_2' => 'blah',
    );
    // this would probably be in a function to be used everywhere
    foreach ($defaults as $defaultOption => $defaultValue) {
        if (!isset($options[$defaultOption])) $options[$defaultOption] = $defaultValue;
    }
}

With parse_str:

$blahOptions = 'option_1=1';
BlahString($blahOptions);
function BlahString($options = '') {
    $defaults = array(
        'option_1' => false,
        'option_2' => 'blah',
    );
    parse_str($options, $defaults);
    $options = $defaults;
}
+2  A: 

No. There are more disadvantages than advantages.

When you’re using a single string, you just can pass string values. With an array you can use every PHP data type and every element’s value type is independently of each other.

Gumbo
Darryl Hein
But you cannot distinguish between data types unless you are using some special format.
Gumbo
+1  A: 

With parse_str, you can potentially drop in the query string from the URL, and the function will work. If you use an array, and you want to use the query string, you'll have to enumerate everything into an array before calling the function.

I'm not totally convinced it's the best way to go, but I see how it can add a bit of flexibility.

Kekoa
+6  A: 

No. That seems like a ridiculous way to pass functional parameter arguments. I could understand it if you needed to recreate $_GET or $_POST variables or something along those lines, but for parameters to a function? That's code smell right there.

They should be using an array, and then utilizing extract() instead. I've worked with Wordpress before, and my advice is to keep the code at arm's length. It is not an example of model programming.

zombat
I can see the advantage of passing GET and POST directly in, but that'd be quite scary.
Darryl Hein