Re: Implicit isset/isempty check on short-ternary operator
| From: | Ole Markus With | Date: | Thu, 14 Apr 2011 08:20:01 +0000 |
| Subject: | Re: Implicit isset/isempty check on short-ternary operator | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-51882@lists.php.net to get a copy of this message | ||
On Thu, 14 Apr 2011 02:24:56 +0200, Ben Schmidt <mail_ben_schmidt@yahoo.com.au> wrote:
I have never felt the need for a shortcut in these cases. It would be interesting to see some code where this would be practical.I think these shortcuts could be really useful for array elements, but for other variables I am really sceptical and I think they would do more harm than good. Generally I do not really see any reason why a variable should not be 'instanciated' before use. So +1 if this shortcut is implemented to only work for array elements. -1 for any other variable type.There are two issues here.1. Suppression of notice. I agree, it is best done only for array keys. It's not hard to initialise a variable with $var=null at the beginning of a code block to avoid such a notice, and that is the appropriate way to do it for variables.2. Offering a shortcut for the common idiom isset($x) ? $x : $y in line with the DRY design principle. A notice would never be emitted here in any case. The problem is that this idiom is still in wide use despite the shortcut ternary operator already provided, because an isset() check is different to a boolean cast.Some thoughts:- The actual intent of 2. is probably $x!==null ? $x : $y i.e. it's not about suppressing notices at all, but about offering a default value, and the idiom quite probably only uses isset() because it predated null in the language.
This is what I feel PHP is missing. Particularly when it comes to multi-dimensional arrays. Because this feature is missing I tend to do something like function generateHash($x, $y, $z) { return "$x::$y::$z"; } if (isset($a[generateHash($x, $y, $z)]) { ... } instead of if (isset($a[$x]) && isset($a[$x][$y]) && isset($a[$x][$y][$z])) { ... }- If we view 2. in this way, the two problems are independent, and it seems to me it would be best to solve them independently, rather than with a single operator.So, I suggest:1. An array lookup mechanism that suppresses the notice for undefined keys. It would work the same as regular array index lookups except that the notice for undefined keys (and only for undefined keys) would not be generated (it would not just be hidden, but would never be even generated).
Arguing about syntax is then a second step. However, my views on this are:I think it best to avoid discussing the actual syntax before agreeing on what we really need. -- Ole Markus With Systems Architect - Sportradar AS Developer - Gentoo Linux