简体   繁体   中英

Is there an efficient way to write this PHP if / else statement?

I've written a simple issue tracker for my web app. I have some comments that I want to keep private (only a role of 'root' can see them). Is there a better way to write the following so I do not need the empty else section?

$role will be 'root' or some other values
$is_private will be true if the comment is private

<?php
// Don't show private comments to non-root users
if ($is_private && 'root' != $role):
    // NON Root cannot see private
else:
?>
<div class="comment <?= $is_private ? 'private' : '' ; ?>">
    <div class="comment-meta toolbar">
    <?= $is_private ? 'PRIVATE - ': ''; ?>
    <span class="datestamp"><?= $created_at; ?></span> - 
    <span class="fullname"><?= $fname . ' ' . $lname; ?></span></div>
    <p class="content"><?= nl2br($body); ?></p>

</div>
<?php endif; ?>

All you need to do is to invert the condition: comments are visible if they are NOT private, or if $role is 'root'.

<?php
// Don't show private comments to non-root users
if (!$is_private || 'root' == $role):
?>
<div class="comment <?= $is_private ? 'private' : '' ; ?>">
    <div class="comment-meta toolbar">
    <?= $is_private ? 'PRIVATE - ': ''; ?>
    <span class="datestamp"><?= $created_at; ?></span> - 
    <span class="fullname"><?= $fname . ' ' . $lname; ?></span></div>
    <p class="content"><?= nl2br($body); ?></p>

</div>
<?php endif; ?>

You could simply invert the whole expression:

if (!($is_private && 'root' != $role))

Or you solve it using De Morgan's laws to this:

    !($is_private && 'root' != $role))
<=>  !$is_private || !('root' != $role)
<=>  !$is_private || 'root' == $role
if (!$is_private || 'root' == $role):

这可能是错误的,请参阅讨论

if ($is_private && 'root' == $role):

by better I'm assuming you mean cleaner code?

if so, put it in a function and call it.

function showPrivateComment($is_private, $role)
{
    if($is_private && $role == 'root')
        return true;
    elseif(!$is_private)
        return true;

    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM