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):
This might be wrong, see discussion
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;
}
精彩评论