Re: suggestion about ternary operator
| From: | Alban | Date: | Sun, 22 Nov 2009 03:41:36 +0000 |
| Subject: | Re: suggestion about ternary operator | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-46153@lists.php.net to get a copy of this message | ||
Le Sat, 21 Nov 2009 10:21:18 -0800, Rasmus Lerdorf a écrit :
>
> The ternary isn't meant to solve the isset thing you are talking about.
> It is simply a shortcut to normal ternary operations. The most common
> case where you don't know if a variable is set is on the initial input
> via $_GET or $_POST and we definitely don't want people doing:
>
> $var = $_GET['foo'] ?: 42;
>
> It would be an XSS disaster. Hence the suggestion to use input_filter
> there, or a similar user-supplied filtering function in which case the
> ternary, as it is currently implemented, is perfectly suitable.
>
> -Rasmus
Sure ! Developpers should filter variables contents !
Generaly there are 3 step for treat incoming variable :
1- checking existance of the variable.
2- set a default value if it not exists or empty.
3- filtering the variable content.
Generaly, we combine step 1 and 2 in one.
I don't recommand using empty() because this method has some side effect
like '0' or 'off' which are interpreted as empty values. I prefer use
isset() method.
Every time, we need to check existance of variable. Checking if var is
empty to fill it with a default value is optionnal, this step differs
depending on the program behaviour.
For the third step, filter extension for example are perfect.
So, PHP provides an excellent short syntax to fill empty variable with
the ternary operator.
But there is a lack for the most common case which is check if variable
is set.
Perhaps I've made a mistake by suggesting a ternary operator improvement.
The real needing is :
I want a pretty and short syntax like the ternary operator for checking
if a variable is set and set a default value if it not set.
I have one for array with union opertor.
$_POST += array(
'foo' => '',
'bar' => '',
'baz' => '',
);
And having something like that would be nice :
$var ?= 'default';
// this can work too for array
$_GET['foo'] ?= 'default';
I am aware that I am repeating myself and that I seem insistant. It is
difficult to express ideas clearly when one is not very comfortable with
English and I apologize for that :)
--
Alban Leroux seza@paradoxal.org