3

有什么办法可以缩短这段代码?

<?= isset($email)?$email:''; ?>

我觉得重复 $email 有点愚蠢。我试过了

<?= isset($email)?:''; ?>

但它与来自 isset 的布尔值相呼应。

4

3 回答 3

2
<?= isset($email)?$email:''; ?> // is the shortest way to do it.
于 2013-10-22T21:01:20.463 回答
1

您可以编写一个自定义函数:

function safeEcho(&$var) {
    if (isset($var))
        return $var;

    return null;
}

并调用此函数:

<?= safeEcho($var) ?>
于 2013-10-22T21:06:20.120 回答
1

“做空”的唯一方法是自定义函数。

function get(&$email) { // <- Note, there must be a reference!!!
  return isset($email) ? $email : '';
} 

<?= get($email); ?>

如果您在$email没有引用的情况下通过,那么如果未设置变量,isset()则会发出 a 。E_NOTICE这是因为您传递给isset()未定义变量的副本,而不是变量本身。

于 2013-10-22T21:13:51.740 回答