Re: [RFC] Nullable Casting

From: Date: Tue, 09 Apr 2019 07:32:16 +0000
Subject: Re: [RFC] Nullable Casting
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-105157@lists.php.net to get a copy of this message
Dan Ackroyd <Danack@basereality.com> wrote: > > I'm guessing you don't actually have ths function getIntOrNull() in > your code-base? To help me understand where this would be useful, > could you provide some 'real-world' code where this would be useful? Hello, thanks for digging in :) Here's a "real-world" situation I happened to come across (*NOTE: simplified for sanity*): vendor/bar/api/src/Dest.php (code we don't own): <?php namespace Bar\Api; interface Dest { public function send(?string $reference, string $label, /* ... */); } vendor/foo/api/src/Source.php (code we can't modify either): <?php namespace Foo\Api; interface Source { public function getNumber(): ?int; public function getName(): string; /* ... */ } src/Service.php (our code): <?php declare(strict_types=1); // FIXME namespace App; use Bar\Api\Dest; use Foo\Api\Source; class Service { public function action(Dest $dest, Source $source) { $dest->send(/* FIXME */ $source->getNumber(), $source->getName(), /* ... */); } } As you can see, it's actually pretty close to the RFC example; I'm not sure it's worth to add complexity... > But please can you post the actual use-case you _need_ this for. Or > possibly update the RFC with that example. Currently, imo, the RFC is > just presenting an alternative syntax for something that is not 100% > needed. You have a point, but all the current alternatives I can think of (namely: use a ternary (or an if), possibly with a temporary variable; write (and autoload) custom casting functions; or give up on strict typing) suffer one or more of the following downsides: - increased risk of mistakes - verbosity / more maintenance - performance overhead > I do kind of like the idea in the RFC, but I think it needs a better > argument for it. For your other points, I find that Claude Pache has given pretty good arguments in the meantime (thanks!) =) (By the way, I also thought about say, "nullable_intval()", "nullable_strval()" etc. but we're missing "arrayval()" and "objectval()"...) Best regards, -- Guilliam Xavier

« previous php.internals (#105157) next »