Should we have some sort of isset()-like operator with default?
| From: | Andrew Faulds | Date: | Sat, 04 Aug 2012 19:30:40 +0000 |
| Subject: | Should we have some sort of isset()-like operator with default? | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-62033@lists.php.net to get a copy of this message | ||
Hi there,
In the "Implict isset in ternary operator" thread, the idea of a special version of the ternary operator with an isset implied was proposed. I don't like this idea very much, but from that I want to suggest some sort of "default" operator.
On IRC I had a little discussion about it with nikic (Nikita), salathe (IRC realname is Peter) and Tyrael (Ferenc).
Basically, I end up writing code like this a lot:
if (!isset($relations[$prev])) {
$relations[$prev] = [];} I don't like isset(), it looks quite ugly to me (although I'm fine with empty()). And I think a non-keyword operator for it would be more readable, and save space. My basic idea is summed up by salathe here: https://gist.github.com/3256826 An operator (let's use ? for the time being, whether that becomes the actual operator or not) is proposed that functions like isset, so: $var? // same as isset(var) This on its own is already shorter than isset(), and imo, nicer to read: if ($var?) { /* ... */ } However, I also propose a variant on the "var ?" form, which is "var ? default", for specifying a default: $var ? "default" // same as isset($var) ? $var : "default" This would allow you to express this: if (!isset($_REQUEST['p'])) {
$page = 'home';} else {
$page = $_REQUEST['p'];} More concisely as: $page = $_REQUEST['p'] ? 'home'; But I also propose something like a ?= operator, such that you can fill in defaults where a variable doesn't exist: $array['thing'] ?= "default value"; So, to some up:
| $var ? => isset($var)$var ? default => isset($var) ? $var : default $var ?= default => $var = $var ? default => $var = isset($var) ? $var : default| Thoughts? This is all hypothetical, of course. It is probably not difficult to implement, but I think it needs discussing before implementing, I am not going to rush. Thanks. -- Andrew Faulds http://ajf.me/