如何写长IF更漂亮?

goo*_*ing 4 php

我有很长的IF:

if(rand(1, 100) == 22 && $smth < time() && 
$smths > 5 && $sxsxsx > 250 && 
!$_SESSION['false'])
{
    echo "wow, big if just happened!";
}
Run Code Online (Sandbox Code Playgroud)

如何写得更"漂亮"?

Ign*_*ams 17

我更喜欢在布尔运算符之前断开.

if(rand(1, 100) == 22
   && $smth < time()
   && $smths > 5
   && $sxsxsx > 250
   && !$_SESSION['false']
)
Run Code Online (Sandbox Code Playgroud)


Dan*_*ite 6

我喜欢说出我的条件并将它们分组,以便清楚它们的目的是什么.

$is22 = rand(1, 100) == 22;
$someTime = $smth < time() && $smths > 5;
$meetsSx = $sxsxsx > 250;
$inSession = !$_SESSION['false'];
if ($is22 && $someTime && $meetsSx && $inSession) {
     // do something
}
Run Code Online (Sandbox Code Playgroud)


Fra*_*ani 5

$isSomethingValid = rand(1, 100) == 22
   && $smth < time()
   && $smths > 5
   && $sxsxsx > 250
   && !$_SESSION['false'];

if ($isSometingValid) {
    // do something
}
Run Code Online (Sandbox Code Playgroud)