Re: Implicit isset/isempty check on short-ternary operator
| From: | Ben Schmidt | Date: | Thu, 14 Apr 2011 12:41:40 +0000 |
| Subject: | Re: Implicit isset/isempty check on short-ternary operator | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-51894@lists.php.net to get a copy of this message | ||
On 14/04/11 10:08 PM, Jordi Boggiano wrote:
On 14.04.2011 13:58, Ben Schmidt wrote:Actually, you'll get a cute fatal error when the function is called because of the type hint in that case. Anyway, yeah, sure, perhaps a bad example in its detail. I didn't spend hours composing it. Just use a little imagination, though, and imagine that it wasn't a type hinted object coming in, but some other value like an integer. Then a boolean test would not work (would be false for zero and erroneously use the default value). You then need the isset test. I personally prefer to always use an isset/key_exists/is_null test when I'm testing for something's 'existence' and not its 'truth'. I think that makes the code more readable. Ben.I have many, many uses for this. E.g. patterns like this: class Foo {I'm sorry but this is not a valid use case, isset() is totally unnecessary here. You can use $bar = $bar ?: $this->defaultBar; Of course it still repeats $bar, but it's not that verbose, and will work exactly the same as what you do. I'd argue it's even better than what you do because, if it weren't for that Bar type hint, if someone passes false or "blah" to your function, isset() will return true, and you'll try to call doSomething on false/"blah", which is a cute fatal error.private $defaultBar; public function foobar(Bar $bar=null) { $bar = isset($bar) ? $bar : $this->defaultBar; $bar->doSomething(); }}