简体   繁体   中英

Is it bad practice to define an array as part of a function call?

Working with WordPress and looking at code examples, I've seen two different ways of using arrays with functions:

1. Define the array first, then pass it into the function as a parameter

$args = array(
    'name' => 'Home right sidebar',
    'id' => 'home_right_1',
    'before_widget' => '<div>',
    'after_widget' => '</div>',
    'before_title' => '<h2 class="rounded">',
    'after_title' => '</h2>', 
 );
register_sidebar( $args );

2. Define the array as part of the function call

register_sidebar( array(
    'name' => 'Home right sidebar',
    'id' => 'home_right_1',
    'before_widget' => '<div>',
    'after_widget' => '</div>',
    'before_title' => '<h2 class="rounded">',
    'after_title' => '</h2>', 
 ) );

Is it bad practice to define an array as part of a function call ( #2 ) or is it a style choice?

If it's bad practice, why?

No it's not bad practice.

If you are going to reuse the array you have to choose the first possibilty. Otherwise the choise is up to you.

No choice is bad practice, it is all about readability. I personally prefer choice #1 due to readability.

This is purely just a case of what works best for you. Just a note on #2, just for readability, I would rewrite it as

register_sidebar( 
    [
        'name'          => 'Home right sidebar',
        'id'            => 'home_right_1',
        'before_widget' => '<div>',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="rounded">',
        'after_title'   => '</h2>', 
    ]
);

EDIT

Note: The above array syntax ( [] ) is only available as from PHP 5.4. If you happen to use older versions ( which you really shouldn't ), change the short array syntax back to the old syntax ( array() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM