Home > Enterprise >  PHP - skip else statement on boolean
PHP - skip else statement on boolean

Time:09-01

I have command handler that returns approve param which is boolean type and can be true or false. I have specific setters there and I defined it like:

if ($command->approve()) {
        $schedule->setApproval(true);
        $schedule->setApprovalAt(new \DateTime());
    } else {
        $schedule->setApproval(false);
        $schedule->setApprovalAt(null);
}

Is there any cleaner approach to this? Can we skip this kind of repetition and using of else clause?

CodePudding user response:

You could make this a two-liner with the help of PHP's ternary operator:

$schedule->setApproval($command->approve());
$schedule->setApprovalAt($command->approve() ? new \DateTime() : null);
  • Related