Re: Deprecation ideas for PHP 8
| From: | Claude Pache | Date: | Wed, 23 Jan 2019 14:43:20 +0000 |
| Subject: | Re: Deprecation ideas for PHP 8 | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-103799@lists.php.net to get a copy of this message | ||
> Le 23 janv. 2019 à 14:19, Girgias <george.banyard@gmail.com> a écrit :
>
>
>
> On Wed, 23 Jan 2019 at 09:19, Claude Pache <claude.pache@gmail.com> wrote:
>
>>
>>> - settype
>>
>> AFAICS, there is no easy replacement for settype(). If the second argument
>> is a string literal, you can use type coercion + assignment at the price of
>> duplicating the occurrence of the first argument. If the second argument is
>> not known at compile time, you have to resort to a switch statement or
>> something similar.
>>
>
> I did not consider that someone might want to set the type of a variable at
> runtime because
> I can not see any pratical usages for that, imho you change a variable type
> into another one
> because you want to work with that specific type. But it basically boils
> down to the same issue
> as with gettype that without it you need to do a switch statement to get
> something similar.
>
>
So, since you didn’t see, here are some practical usages of settype():
<?php
function foo($bar) {
// $bar is supposed to be either a string, or a list of strings
settype($bar, 'array');
// ...
}
function qux($id) {
if (!(is_int($id) || is_string($id) && ctype_digit($id)))
throw new \TypeError;
settype($id, 'int');
// ...
}
class Foo implements SeekableIterator {
function seek(/* int */ $position): void {
// NOTE: we cannot use int typehint here, because PHP7.1 requires mixed
settype($position, 'int');
// ...
}
}
?>
Here are a usage of settype() with a non-constant second parameter: Define a utility function that
cast a value to a given type when it is not null:
<?php
function cast_opt($val, $type) {
if ($val !== null)
settype($val, $type);
return $val;
}
$foo = cast_opt($bar, 'int') // equivalent to: $foo = $bar === null ? null : (int) $bar;
?>
Sure, one can avoid settype() and do it the complicated way, but why? What is the issue with
settype(), so that you want to deprecate it?
—Claude