Thanks for sharing. I like this a lot. It always feels tedious doing the checking, especially in nested objects. Syntactic sugar like this makes programming more fun and lets you focus on the important stuff. This is also one of the reasons why I don’t like php syntax, with its isset, empty, is_null etc.
Haven't tried PHP 7 yet (have to get to it), but coming from C# this just looks wrong.
If $specimen === null, then $specimen->arms should throw a NullReferenceException - or trigger an error, I don't recall quite how PHP handles it - but that doesn't seem to happen which, after having been away from PHP for a couple of years, is weird.
Your example is pretty arbitrary though, as the manual says that sizeof (and thereby count)
Returns the number of elements in array_or_countable. When the parameter is neither an array nor an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.
so $var should be 0 regardless. It also triggers an error though, but with how PHP uses functions such as count to get such information, it seems really bothersome to actually use null coalescing to get proper results. You'd need to supply weird default values as function parameters - but I guess that's why count returns 0 for null values, though that still throws an error, so you'd need to do an isset() prior to getting the count() unless you want to use the default value, which is just ugly.
This turned much longer than I initially figured. Boy do I appreciate C#'s var count = specimen?.Arms?.Count ?? 0 though.
Sure, there are drawback to this method, although I've been using it in a large project for quite some time now and frankly didn't find many practical issues so far. I'm not saying you're wrong obviously, but can you provide some actuals example of when this could cause issues?
I'm a typescript guy (or any statically typed language) so I view stringly typed as the single worst thing possible. The potential to make typos that are difficult to find is just too high for me.
62
u/impreson Feb 20 '18
Thanks for sharing. I like this a lot. It always feels tedious doing the checking, especially in nested objects. Syntactic sugar like this makes programming more fun and lets you focus on the important stuff. This is also one of the reasons why I don’t like php syntax, with its isset, empty, is_null etc.