Hi!
I've always thought isset() was quite ugly. For something I use quite
frequently for checking the existence of array keys, I feel it is too
many keystrokes, and is ugly.
So, I decided I would create a shorthand for isset().
One option suggested was a new operator, 'expr ??', which I don't like
the idea of very much. I would also have liked 'expr ?', but that would
conflict with the ternary operator, 'expr ? expr : expr'. Then, I had
the idea of '? expr', but that also caused a conflict. So I settled on
'? ( expr )', which is used like this:
if (?($_POST['credit_card_no'])) {
// ...
} else if (!?($_POST['use_paypal']) && ?($_POST['bank_acc_no'])) {
// ...
}
And since it doesn't break the ternary operator, like this:
$number = ?($x)? intval($x) : 0;
I quite like how it combines with !, so !?() tests for non-existence,
and ?() tests for existence.
It's quite trivial, but it would save me (and probably many others)
time, and I think it would add some extra character to PHP, with its
quirky syntax. :)
Patch attached. Thoughts welcome.
--
Andrew Faulds
http://ajf.me/
>From 24107911374fd9e9dbc731b4564a440dd72f5568 Mon Sep 17 00:00:00 2001
From: Andrew Faulds <a...@ajf.me>
Date: Sat, 4 Aug 2012 01:37:23 +0100
Subject: [PATCH] Added ?() op as shorthand for isset() - Added ?() - Added
test
---
Zend/zend_language_parser.y | 1 +
tests/lang/shorthand_isset.phpt | 21 +++++++++++++++++++++
2 files changed, 22 insertions(+)
create mode 100644 tests/lang/shorthand_isset.phpt
diff --git a/Zend/zend_language_parser.y b/Zend/zend_language_parser.y
index c88e9a7..5781cd6 100644
--- a/Zend/zend_language_parser.y
+++ b/Zend/zend_language_parser.y
@@ -773,6 +773,7 @@ expr_without_variable:
| '(' expr ')' { $$ = $2; }
| new_expr { $$ = $1; }
| '(' new_expr ')' { $$ = $2; } instance_call { $$ = $5; }
+ | '?' '(' isset_variables ')' { $$ = $3; }
| expr '?' { zend_do_begin_qm_op(&$1, &$2 TSRMLS_CC); }
expr ':' { zend_do_qm_true(&$4, &$2, &$5 TSRMLS_CC); }
expr { zend_do_qm_false(&$$, &$7, &$2, &$5 TSRMLS_CC); }
diff --git a/tests/lang/shorthand_isset.phpt b/tests/lang/shorthand_isset.phpt
new file mode 100644
index 0000000..9218f89
--- /dev/null
+++ b/tests/lang/shorthand_isset.phpt
@@ -0,0 +1,21 @@
+--TEST--
+?() (Shorthand isset()) operator test
+--FILE--
+<?php
+$arr = [];
+var_dump(?($arr['nonexistant']));
+var_dump(!?($arr['nonexistant']));
+
+$arr['hello'] = 7;
+var_dump(?($arr['hello']));
+var_dump(!?($arr['hello']));
+
+var_dump(?($arr['hello']) ? 'expected' : 'unexpected');
+var_dump(!?($arr['hello']) ? 'unexpected' : 'expected');
+--EXPECT--
+bool(false)
+bool(true)
+bool(true)
+bool(false)
+string(8) "expected"
+string(8) "expected"
--
1.7.9.5
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php