为变量赋值的if else语句的简写


shorthand for if else statement assigning value to variable

哈,为什么name显示值1

['name' => ($profile->getNickname() || $profile->getName()),]

a => b || c如果b是空的,就用c,不是吗?

注。我知道我可以做正常的if else速记(三元),但它很长而且不可读,我不喜欢它。

在javascript中这是一个常见的东西,但是PHP将转换为布尔值。

这个问题将回答您的问题:给变量一个默认值的最佳方法(模拟Perl ||, ||=)

$name = $profile->getNickname() ?: $profile->getName();

在PHP中,布尔运算符||&&总是产生一个布尔值;如果有必要,操作数将被强制为布尔值,并丢弃原始值。这与JavaScript不同,在JavaScript中,操作数被求值为"真实性",但保留其原始值。

您看到的1只是因为您回显了一个布尔值,这反过来又将true强制转换为字符串1

PHP有一个你想要的简写操作符:?:

($profile->getNickname() || $profile->getName())只是一个条件来实现(1),这就是为什么它显示1。

应该如下所示:

// if nick name is set and not empty then show it otherwise show name
[ 'name' => ((isset($profile->getNickname()) && ($profile->getNickname() != "")) ?  $profile->getNickname() : $profile->getName())]

返回isset(data)函数的布尔值
$profile-> getickname () and
概要文件-> getName ()
决定一个条件