在 shorthand if 语句中重用函数结果
Reuse function result in shorthand if statement
有没有办法在不声明变量来保存函数结果的情况下,使用在 shorthand if 语句中调用的函数的结果,例如:
!empty(getType($user)) ? <RESULT OF FUNCTION> : ''
而不是做:
!empty(getType($user)) ? getType($user) : ''
这实际上调用了函数两次。
只需将函数的 return 值分配给一个变量,例如
!empty($result = getType($user)) ? $result : ''
//^^^^^^^^^^ ^^^^^^^ See here
编辑:
由于 gettype()
总是 return 是一个字符串,您可以执行以下操作,但是三元组就没有意义了,因为它总是 return 是一个字符串。
getType($user)?: ''
很丑,但是
php > echo (empty($foo = 0)) ? $foo : 'false';
0
由于 PHP 中的赋值操作的结果是被赋值的值,您得到 $foo 定义,然后可以在 true
子句中使用它。
有没有办法在不声明变量来保存函数结果的情况下,使用在 shorthand if 语句中调用的函数的结果,例如:
!empty(getType($user)) ? <RESULT OF FUNCTION> : ''
而不是做:
!empty(getType($user)) ? getType($user) : ''
这实际上调用了函数两次。
只需将函数的 return 值分配给一个变量,例如
!empty($result = getType($user)) ? $result : ''
//^^^^^^^^^^ ^^^^^^^ See here
编辑:
由于 gettype()
总是 return 是一个字符串,您可以执行以下操作,但是三元组就没有意义了,因为它总是 return 是一个字符串。
getType($user)?: ''
很丑,但是
php > echo (empty($foo = 0)) ? $foo : 'false';
0
由于 PHP 中的赋值操作的结果是被赋值的值,您得到 $foo 定义,然后可以在 true
子句中使用它。