How useful is the new ?: operator?
As with everyone else excited about PHP 5.3, I was extremely looking forward to developing in it. I was especially excited to use the new shorthand ternary operator (?:). This would remove the redundant middle expression of returning the variable, and instead would return itself if it evaluated to true. But after much testing and trying to implement it in interesting ways, the shorthand ternary just isn't as useful as you would hope. The primary problem is the left-most expression must evaluate to true or false, which isn't possible with the shorthand. Below is my test case.
error_reporting(E_ALL | E_STRICT);
class Ternary {
private $__data = array('key' => 'value');
public function get($key, $default = null) {
return $this->__data[$key] ?: $default;
}
}
$test = new Ternary();
var_dump($test->get('key')); echo '<br>';
var_dump($test->get('test')); echo '<br>';
var_dump($test->get('')); echo '<br>';
var_dump($test->get(false)); echo '<br>';
var_dump($test->get(null)); echo '<br>';
This test works for the most part, the value or null is always returned. However, the problem is that this technique throws notice errors; here is the result after running the test. You can easily avoid this by turning of notice errors, but that's bad practice.
string(5) "value"
Notice: Undefined index: test in C:\xampp\htdocs\scripts\index.php on line 9
NULL
Notice: Undefined index: in C:\xampp\htdocs\scripts\index.php on line 9
NULL
Notice: Undefined offset: 0 in C:\xampp\htdocs\scripts\index.php on line 9
NULL
Notice: Undefined index: in C:\xampp\htdocs\scripts\index.php on line 9
NULL
I was hoping the new shorthand ternary would internally run an isset() and evaluate automatically, but it looks like it does not. So now we are still stuck with the old verbose way of doing things.
return isset($this->__data[$key]) ? $this->__data[$key] : $default;
Is there a reason why the PHP devs chose not to run an isset automatically? Or am I doing something wrong here? More information on this would be helpful, because I believe the operator would be multitudes more useful if it worked like I suggested.