On Friday, 7 Feb 2025 at 10:45, Faizan Akram Dar <he...@faizanakram.me> wrote:
> > > On Fri, 7 Feb 2025, 08:30 Mihail Liahimov, <91lia...@gmail.com> wrote: > >> Thank you for your answer. Now I will give examples for better >> understanding. >> >> Simple examples from Typescript: >> >> let foo = ... >> foo!.bar() >> foo!.someProperty.baz() >> >> Examples of potentially using in PHP: >> Without this operator we writing this code: >> >> $foo = ... >> >> if ($foo === null) { >> throw new FooIsNullException(); >> } >> >> $foo->bar. >> >> With this operator: >> >> $foo!->bar >> $foo!->someProperty->method(); >> $foo!->someProperty->anotherProperty!->method(); >> >> I think the postfix operator would be illogical in PHP because my >> operator is similar to the existing nullsafe operator in syntax. And it >> would be strange if its syntax were different. >> Or we can implement both operator syntaxes: prefix for accessing >> properties, and postfix for use with variables, as in your example. >> >> Nullsafe: >> $foo?->bar; >> Not null assertion: >> $foo!->bar; >> >> If variable bar would be null - php will throw an exception. But now i >> dont know which exception it would be :) >> >> This operator will be useful in cases where a null value in a specific >> place will violate the domain logic. Usually we write either assertions or >> checks and throw our exceptions for this. But it seems to me that the not >> null assertion operator will help avoid writing unnecessary code. The >> problem, of course, will be catching errors. It is not clear how to catch >> errors by a specific value. I will think about it. >> > > > Hi, > > I don't see the point of this operator, php doesn't allow any operation > over null. > > See https://3v4l.org/UJ5eg > > It's throwing warning (mostly for backwards compatibility), I'd rather > have it throw error in next php version. > > Static analysis already complain about it, so whats the point of !-> > operator? > https://phpstan.org/r/c9d6e7b3-ac66-4e91-81e8-af0cafdc976c > > > > Static analysis already complain about it That's exactly where `!` is helpful. If at a certain point I am sure that a property must not be null and I want to make that explicit (to both developer and static analyzer), I can use `assert($obj->prop !== null)`. However, that requires an extra line of code. `$obj->prop!->x` would be much prettier. -- Valentin