PHP null使用此值


PHP null use this value

在c#中你能做什么??检查是否为null,然后使用类似于…的值

DateTime? today = null;
DateTime todayNotNull = today ?? Date.Now;

有没有一种在PHP中实现这一点的简写方法?

是。

$var = ConditionalTest ? ValueIfTrue : ValueIfFalse;

请注意,必须同时使用ValueIfTrueValueIfFalse


在您的具体情况下:

<?php
    $today = null;
    $todayNotNull = isset($today) ? $today : date();
?>

您可以按照其他用户的指示使用三元运算符。

$today = null;
$todayNotNull = $today ? $today : time();

从PHP 5.3开始,您还可以将其缩短为您想要的熟悉语法:

$todayNotNull = $today ?: time();

由于PHP 5.3,可以省略三元运算符。表达式表达式1?:如果expr1,则expr3返回expr1计算结果为TRUE,否则为expr3。

$todayNotNull = ($today===NULL ? date() : $today);

UPDATE:使用像$today ? $today : date()这样的隐式NULL检查时要小心。

true is true. (type: boolean)
false is false. (type: boolean)
null is false. (type: NULL)
[] is false. (type: array)
[0] is true. (type: array)
[1, 2, 3] is true. (type: array)
{1: 2, "x": 3} is true. (type: array)
"" is false. (type: string)
"0" is false. (type: string)
"1" is true. (type: string)
"2" is true. (type: string)
"x" is true. (type: string)
0 is false. (type: integer)
1 is true. (type: integer)
2 is true. (type: integer)
0 is false. (type: double)
0.1 is true. (type: double)
0.2 is true. (type: double)

我强烈建议您明确测试NULL。