繁体   English   中英

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

[英]shorthand for if else statement assigning value to variable

哈哈,为什么名称显示值1

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

a => b || c如果b为空,使用c是吗?

ps我知道我可以做其他速记(三进制)的普通操作,但是它又长又不可读,我不喜欢它。

在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-> getNickname()
$简介- >的getName()
决定条件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM