PHP/WordPress, different coding style

I’ve noticed some strange coding styles in PHP/Wordpress code:

1) Returns at start of function:

Read More

I’m surprised how often I see PHP/Wordpress code that returns at the start of a function. For example:

function dosomething() {
   if (!current_user_can($priv)) {
       return;
   }
   .... continued code

is used instead of what is usually considered good practice, that is, rarely having multiple returns (they are basically gotos):

function dosomething() {
    if (current_user_can($priv)) {
        ... do something
    }
    ... any finishing code
}

2) Lack of brackets in if’s

In most other languages, the single-line if/else statement without brackets is considered messy/dangerous because additional lines may look like they will run when they actually don’t. I’ve seen this used many times in PHP/Wordpress however.

I’m wondering if these different styles have performance benefits, or other specific reasons for their use?

Related posts

Leave a Reply

2 comments

  1. I’d say it’s debatable. The difference in processing if your single line conditionals have no braces is so small it would not likely be done to increase performance.

    The returning at the beginning of a function is to prevent it from even running the process if it fails to meet that condition. You probably know that already by looking at the code but may not have considered that the function will evaluate until return, so your function could have dozens of conditionals it never meets after the first one. No sense in processing those if you don’t have to.

    This isn’t specific to wordpress at all, by the way. I’ve seen it done like this all over the place.

  2. Neither are performance related. The first just guarantees that nothing in the function can be processed by a user who isn’t authorized to do so (to make sure they don’t run “… any finishing code” in your example), and the second is a style preference for simple if/else statements.