PHP: Using the ternary operator for something else than assignments – valid use case?

旧巷老猫 提交于 2019-12-13 16:29:33

问题


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

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'));

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

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

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


回答1:


Yes, you can. From the PHP Doc:

[...] 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).

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 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.

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');


来源:https://stackoverflow.com/questions/29876307/php-using-the-ternary-operator-for-something-else-than-assignments-valid-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!