PHP:如果未设置,则分配空值?

php
2022-08-30 12:11:20

PHP中是否有任何一种赋值-如果不是空-否则-赋值-空函数?

我正在寻找以下更清洁的替代品:

$variable = (!empty($item)) ? $item : NULL;

如果我可以指定默认值,那也将很方便;例如,有时我想要' '而不是NULL。

我可以编写自己的函数,但是有原生解决方案吗?

谢谢!

编辑:应该注意的是,我试图避免未定义值的通知。


答案 1

更新

PHP 7 添加了一个新功能来处理这个问题。

空聚结运算符 (??) 已添加为语法糖,用于需要将三元与 isset() 结合使用的常见情况。如果它存在并且不为 NULL,则返回其第一个操作数;否则,它将返回其第二个操作数。

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';

此外,由于同一变量的7.4,它可以更短:

$variable ??= null;
// This is equivalent to:
$variable = $variable ?? null;

它将保留现有值(如果有),如果未设置,则进行赋值。null$variable

原始答案

我最终只是创建了一个函数来解决问题:

public function assignIfNotEmpty(&$item, $default)
{
    return (!empty($item)) ? $item : $default;
}

请注意,$item是通过对函数的引用传递的。

用法示例:

$variable = assignIfNotEmpty($item, $default);

答案 2

重新编辑:不幸的是,两者都会在未定义的变量上生成通知。你可以用,我猜。@

在 PHP 5.3 中,您可以执行以下操作:

$variable = $item ?: NULL;

或者你可以这样做(正如meagar所说):

$variable = $item ? $item : NULL;

否则不,没有其他方法。


推荐