Hi Mihail On Thu, Feb 6, 2025 at 1:51 PM Mihail Liahimov <91lia...@gmail.com> wrote: > > Examples of potentially using in PHP: > Without this operator we writing this code: > > $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;
With a postfix operator this would all work automatically, assuming that $foo!->bar can be parsed correctly as ($foo!)->bar. The, $foo! will check that $foo is not null, and if not, access the property bar on it. > 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. I think, if such an operator were introduced, it should throw an Error rather than an Exception. Errors should generally not be caught, as they indicate logical errors in your program. There are two things to consider: * Is assert($foo !== null); $foo->bar; really much worse? I understand it requires two statements, so it cannot be used in all contexts. * Are we ever going to promote the (null)->prop warning to an Error? If so, is there still any appeal for this feature? E.g. it would automatically work on array access ($array!['foo']). Array access on null may be more controversial to promote to an Error. There are some other potential contexts, like foo($bar!), but you could argue this is already covered by parameter types. Ilija