DEV Community

Cover image for Simple PHP Control Structure Refactoring

Simple PHP Control Structure Refactoring

George Hanson on May 02, 2019

This article was originally posted on my blog - Simple PHP Control Structure Refactoring Before we get into it, I posted all three of these little...
Collapse
 
tarialfaro profile image
Tari R. Alfaro

Do take note, that a lot of PHP developers may not be aware of this. Generally in the real-world, it's best practice to stick with:

if ( $condition ) {
    # . . .
} else {
    # . . .
}

Because every programmer should understand that. And it's actually pretty readable despite requiring a few more lines of code compared to the ternary operator. (I didn't know about the null coalescing or 'Elvis' operator)

Otherwise, if it's a personal project, and you're not expecting others to read it, by all means go with these operators.

But thank you. I learned a couple new things today.

Collapse
 
poldiwa profile image
Paul John Diwa

also an alternative, based on the given example.

$url = '/default.jpg';

if ($user->avatarUrl) {
  $url = $user->avatarUrl;
}
Collapse
 
georgehanson profile image
George Hanson

Hey :)

Sure, it is generally in the real-world better to use full if control structures. It comes down preference, the complexity and readability based on a case-by-case.

I just used these as examples to demonstrate the operators, but in the real-world if you are doing quite a few of these repetitive simple structures then it is sometimes better to reach for a ternary operator. It just comes to the circumstance at the time and it is up to the developer to decide whether or not it is worth reaching for it.

But I'm glad you learned something new.

Collapse
 
tarialfaro profile image
Tari R. Alfaro • Edited

I think it would have a great use case if you're building a lot of options in a function or class method.

so instead of this:

$key = 'default value';

if (\array_key_exists('key', $options)) {
    $key = $options['key'];
}

# But a bunch more ...

But instead we could do a bunch of these:

$key = $options['key'] ?? 'default value';

Also, I'd like to say sorry. I don't think we should always be doing the regular if then else statement. As you said, it's case-by-case. Developers should just learn the language instead.

I think everyone should understand how the ternary operators work. Their symbols are similar to that of && or ||.

Must've missed it, because I didn't see any examples of the 'Evlis' operators or null coalescing.

Anyways, thank you for the great article. w^