Real world example: class Paginator { // If null, will use the default value (eg. 15), else, it will requires an int. public function setItemsPerPage(?int $itemsPerPage) { ... } }
// Info that came from user input. // It will be a string, and not a integer, like we need. $itemsPerPage = Input::get('itemsPerPage'); // If '<empty>' then $itemsPerPage = string '<empty>' // If '123' then $itemsPerPage = string '123' $paginator->setItemsPerPage($itemsPerPage); // Error: expected int, got string. Current solution: $itemsPerPage = Input::get('itemsPerPage') ?: null; $itemsPerPage = $itemsPerPage !== null ? (int) $itemsPerPage : null; $paginator->setItemsPerPage($itemsPerPage); // OK With this new feature: just... $paginator->setItemsPerPage((?int) Input::get('itemsPerPage')); // OK Question: why just not check if $itemsPerPage is set like: $itemsPerPage = Input::get('itemsPerPage'); if ($itemsPerPage) { $paginator->setItemsPerPage((int) $itemsPerPage); // OK } Answer: because in this example we could do that (although the new solution is much more practical). In another case, I have a static factory method that depends of an ?int to be created, and I can't just skip it with an if() if user input is empty. And about "settype($variable, "?int")" it was requested on original mailing by Claude Pache. Em dom, 7 de abr de 2019 às 23:54, Dan Ackroyd <dan...@basereality.com> escreveu: > On Sat, 6 Apr 2019 at 08:53, Guilliam Xavier <guilliam.xav...@gmail.com> > wrote: > > > > Hello internals, > > > > David and I would like to open the discussion on our joint RFC: > > > > https://wiki.php.net/rfc/nullable-casting > > > > Mainly, it would enable to use e.g. `(?int)$x` besides `(int)$x`. > > > > 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? > > By the way, this RFC is a special case of something that could be far > more generic. If it was possible to register callbacks to be used when > casting, people could do something like this: > > function castToIntOrNull($value) > { > if ($value === null) { > return null; > } > > return (int)$int; > } > > register_cast_function('?int', 'castToIntOrNull'); > > $x = (?int)getIntOrNull(); > > > > Additionally, it was requested on the mailing list to consider adding > > support of nullable types to the settype() function, > > e.g. settype($variable, "?int") > > Someone probably needs to make an argument for it to be in core, > rather than just saying that it's something that could be done. > > cheers > Dan > Ack > -- David Rodrigues