Like some people know, C# has very useful ??
operator which evaluates and returns expression on the right if expression on the left is null. It's very useful for providing default values, for example:
int spaces = readSetting("spaces") ?? 5;
If readSetting
couldn't find "spaces"
and returns null, variable spaces
would hold default value of 5
.
You could do almost the same in JavaScript and Ruby with ||
operator, as in
var spaces = readSetting("spaces") || 5;
although you couldn't have 0
as value of spaces
in JavaScript in this case and false
in both Ruby and JavaScript.
PHP has or
operator and although it doesn't work as ||
in a sense that it doesn't return expression from the right, it still could be useful here:
$spaces = readSetting('spaces') or $spaces = 5;
with the note that ""
and "0"
are also treated like false
in PHP in addition to false, 0
and null
in most languages.
The question is, should I use the construction from above? Does it have side effects apart from treating large class of characters as false? And is there better construction that is usually used and recommended by PHP community this task?