By reading the manual:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
So in short:
$nid = $_GET['nid'] ?: 0;
Would work, but PHP will trigger a notice if
$_GET['nid'] is not set. The logic
|| operator won't help, either. The closest you can get is:
(($nid = $_GET['nid']) || ($nid = o));
But that's not exactly shorter, nor does it solve the Notice issue.
The "best" as in shortest, moste un-maintainable and horrible looking code I can think of is this:
$nid = 0;//default
foreach($_GET as $name => $val)
$$name = $val;
This turns all keys that were present in the
$_GET array into var names. If you simply declare the vars you're after (names must be identical to keys, though) and assign them a default value, this loop takes care of the rest.
To map certain keys to another variable name, you could use another array:
$nid = 0;
$map = array('new_id' => 'nid');
foreach($_GET as $k => $v)
$k = $map[$k];
$$k = $v;
But honestly, maintaining code like this is going to be a nightmare. Though request objects add a lot of overhead for a task as simple as this, their
get methods make it all worth while:
public function get($name, $default = null)
This is easy to read/understand and easy to use:
$nid = $getInstance->get('nid', 0);
Assignes the GET param, or 0 to
$nid... which makes your code tidier, easier to maintain and a lot easier to understand. Based on the use-case you posted, I take it you're not using the ternary on just request variables. Well, in that case: use objects with getters/setters that define a default return value (or allow for one to be specified @call-time). If needs must, implement the
ArrayAccess or some
Traversable interface, so you can use it as an array, too.
Granted, it'll take some time/effort to do this, but once you've done that, any new code you write will be cleaner (no ternaries), debugging will be a doddle and type-hinting will become your best friend. check this answer for some examples and considerations on getters and setters, along with this answer on the importance of pre-declaring properties (and thus implementing getters/setters).
If you're still up for it after that, refer to this answer to see why and how you should avoid object overloading (in PHP, at least) as much as possible.