• My question is about using the WordPress PHP Coding Standards.

    I often use(d) statements like this

    if ( $from = any_function() ) {
       // any code
    }

    But this throws an error:
    Assignments must be the first block of code on a line

    The following 2 variations would both validate, but especially variation A is ugly

    Variation A

    if ( 
       $from = any_function() 
       ) {
       // any code
    }

    Variation B

    $from = any_function()
    if ( $from ) {
       // any code
    }

    So the question is, which way is the suggested way to handle it? Or is it maybe an error that this error is thrown?
    If this is the wrong place to ask, please notify and I will ask on the Git Repo again

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    That’s a construct I often use, especially when using ACF fields. Please file an issue on github.

    Thread Starter Christoph Daum

    (@apermo)

    Ok will do.

    Thread Starter Christoph Daum

    (@apermo)

    Thread Starter Christoph Daum

    (@apermo)

    This was the answer on GitHub by JDGrimes:

    Yes, B is definitely what is intended here. There are also other sniffs that check for assignments within conditions. I get a warning from WordPress.CodeAnalysis.AssignmentInCondition for the initial example. Putting assignments within conditionals is generally considered bad practice, because it can lead to mistakenly having an assignment instead of a condition (= instead of ==), when a conditional check is actually what is intended.

    Assignments must be the first block of code on a line

    According to the standards means this:

    if ( any_function() == $from ) {
       // any code
    }

    From what I’ve read, that’s what they are looking for. This way the variable to be tested is the last pat of the equation, not the first, even though that’s now most people do it.

    The reason for this is that it ensure that the value on $from won’t get over-written by what’s returned from the any_function() call when you make the mistake of only having a single = sign.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Coding Standards for if with assignments’ is closed to new replies.