PHP:使用三元运算符进行赋值以外的其他操作–有效的用例? [英] PHP: Using the ternary operator for something else than assignments – valid use case?

查看:147
本文介绍了PHP:使用三元运算符进行赋值以外的其他操作–有效的用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很遗憾,我没有找到任何官方资源。

Unfortunately I haven't found any official resource on this.

是否允许使用这样的三元运算符来缩短和if / else语句:

Is it allowed to use the ternary operator like this, to shorten and if/else statement:

(isset($someVar) ? $this->setMyVar('something') : $this->setMyVar('something else'));

在PHP文档中,此示例说明了三元运算符:

In the PHP documentation, the ternary operator is explained with this example:

$action = (empty($_POST['action'])) ? 'standard' : $_POST['action'];

这使我相信我的用例可能会起作用,但是它实际上无效,因为setter函数可以

This makes me believe that my use case might work, but it not really valid because a setter function does not return anything.

推荐答案

是的,可以。 PHP文档


[...]三元运算符是一个表达式,[...]它不是求值变量,而是表达式的结果。

[...] the ternary operator is an expression, and [...] it doesn't evaluate to a variable, but to the result of an expression.

虽然虽然三元数主要用于赋值,但是您可以按照建议使用它,因为函数调用是一个表达式,因此合适的函数将被求值(并因此执行)。

That quoted, although the ternary is mostly used for assigning values, you can use it as you suggested because a function call is an expression so the appropriate function will be evaluated (and therefore executed).

如果您的setter函数将返回一个值,则该值将不会分配任何内容,因此将丢失。但是,由于您说的是设置器不返回任何内容,因此整个三元运算符将不计算任何结果,也不返回任何内容。没关系。

If your setter function would return a value, it would simply not be assigned to anything and would therefore be lost. However, since you said your setter doesn't return anything, the whole ternary operator will evaluate to nothing and return nothing. That's fine.

如果这比普通的if / else故事更容易读懂。在团队中工作时,我建议宁愿坚持常规的if / else。

If this is more readable than a regular if/else is a different story. When working in a team, I would suggest to rather stick to a regular if/else.

或者,使用这种语法怎么样? / p>

Or, how about going with this syntax, which would be more common?

$this->myVar = isset($someVar) ? 'something' : 'something else';

或者,使用您的设置器:

Or, using your setter:

$this->setMyVar(isset($someVar) ? 'something' : 'something else');

这篇关于PHP:使用三元运算符进行赋值以外的其他操作–有效的用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆