问题
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