Re: Inline conditional that returns null if falsy

From: Date: Sat, 13 Feb 2021 16:22:02 +0000
Subject: Re: Inline conditional that returns null if falsy
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-113165@lists.php.net to get a copy of this message
Em sáb., 13 de fev. de 2021 às 00:11, Marco Pivetta <ocramius@gmail.com> escreveu: > Hey David, > > Even upfront, this looks like a quite bad idea: either you have an empty > collection, or you have a collection with elements in it, but > null is a > very different concept that isn't homogeneous with the resulting type. > > I've updated multiple projects in the past where array|nullÖ?’»7Ð > ß±À¸iýä¢ was used as > return type for a collection-alike endpoint, removing null and > replacing > it with an empty iterable instead. > This was just one of the examples I have, but I still think it is valid. Creating an empty collection costs resources that could be avoided in situations where null could be used (as is most of my real use cases). But there are other situations where we can use different situations to use this type of resource. One of the examples I have is when I need to include a class in an HTML element conditionally. There are probably better ways, but this is a quick one for simple situations: <div class="user {{ $user => "online" }}">...</div> vs. <div class="user {{ $user ? "online" : null }}">...</div> It is much easier to read, and I believe that the cost for language would be minimal, and perhaps even more optimized than the use of ?:. Atenciosamente, David Rodrigues Em sáb., 13 de fev. de 2021 às 00:11, Marco Pivetta <ocramius@gmail.com> escreveu: > Hey David, > > On Fri, Feb 12, 2021, 20:24 David Rodrigues <david.proweb@gmail.com> > wrote: > >> Hello! >> >> It is just a suggestion to be discussed. >> >> A lot of places on my projects I have codes like: >> >> $companies = $user->companies->count() >> ? new Collection($user->companies) >> : null; >> > > Even upfront, this looks like a quite bad idea: either you have an empty > collection, or you have a collection with elements in it, but > null is a > very different concept that isn't homogeneous with the resulting type. > > I've updated multiple projects in the past where > array|null was used as > return type for a collection-alike endpoint, removing null and > replacing > it with an empty iterable instead. > >>

« previous php.internals (#113165) next »