Re: [Proposal] Modification to ?: functionality

From: Date: Tue, 26 Nov 2013 21:51:57 +0000
Subject: Re: [Proposal] Modification to ?: functionality
References: 1 2 3 4 5 6 7 8 9  Groups: php.internals 
Request: Send a blank email to internals+get-70430@lists.php.net to get a copy of this message
On Tue, Nov 26, 2013 at 7:46 PM, Peter Cowburn <petercowburn@gmail.com>wrote: > > > > On 26 November 2013 18:35, Jezz Goodwin <jezzgoodwin@gmail.com> wrote: > >> Hi, >> >> Before mentioning anything about new syntax, I thought I'd point out that >> this code is already possible for setting defaults: >> >> (isset($foo)) ?: $foo = 'default'; >> >> or >> >> isset($foo) ?: $foo = 'default'; >> >> (I personally prefer wrapping the condition within brackets) >> >> Saying that, I do think a syntax for setting defaults which doesn't >> involve >> typing the variable name twice would be nice. >> >> My favourite one listed so far is: >> >> $foo ?= 'default'; >> > > I like that too. > > Elaborating on that idea, here’s one idea from a while back, making much > wider use of a “?” operator… > https://gist.github.com/salathe/3256826 > > I worry sometimes that new syntax features are suggested for cleverness sake and not for making code 'better'. My definition of better code is code that is easy to read, concise, easy to maintain and ideally has good performance. Personally I think this feature can be used to make better code. For example, I use a utility function to make writing default variable values cleaner: function fallback ( &$var, $default=null ) { if (!isset($var)) { $var = $default; } } So, within other functions I use code like this: fallback($name, 'no name'); The main thing that bugs me about using this code is that it has to invoke a function to do it's work. If you've got lots of default values, it's a lot of function calls. This new syntax would lower the number of function calls, and be just as concise. Footnote: Although not quite the same subject, another way to increase performance with this type of code would be a way to tell the parser to inline functions. I'd love to be able to write 'inline function fallback ...' and be able to give my code better grammar without the performance penalty.

« previous php.internals (#70430) next »