Is there any advantage to using parse_str for optional function and array parameters?

I accidentally made some changes to the WordPress blog and noticed that they are using parse_str

( http://php.net/parse_str ) for parsing and setting their optional parameters to the function.

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

Examples:

With an 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;
    }
}

      

From 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;
}

      

+1


a source to share


3 answers


No. This seems like a funny way to pass arguments to function parameters. I could figure it out if you needed to recreate the $ _GET or $ _POST variables or something like that, but for parameters for a function? This code smells right there.



They should use an array and then use extract () instead . I've worked with Wordpress before and my advice is to keep the code at your fingertips. This is not an example of modeling a model.

+6


a source


No. There are more disadvantages than advantages.



When you are using a single string, you can simply pass string values. With an array, you can use every PHP data type and every element value type independently.

+2


a source


With parse_str, you can potentially remove the query string from the url and the function will work. If you are using an array and want to use a query string, you will need to list everything into an array before calling the function.

I'm not entirely sure if this is the best way, but I can see how it can add a little flexibility.

+1


a source







All Articles