PHP should always know the "current type" of a value before it can use it for any purpose, including initializing a variable. This "current type" is metadata (enumeration) that is combined with all values.
In your sample code, castings are pointless because you initialize variables using literal values ββthat are always of an obvious type:
$s = "foo"; echo is_string($s); // 1 $s = (string)"foo"; echo is_string($s); // also 1
The same goes for integers and array.
There is at least one case where the type of a variable would be something other than you might expect at a glance:
$i = PHP_INT_MAX + 1; // or use something like 999999999999 echo gettype($i); // "double"!
In this case, using cast will make $i an integer, but it will also change its value:
$i = (int)(PHP_INT_MAX + 1); echo gettype($i); // "integer" echo $i; // a very large negative number -- what?!?
Of course, this is not caused by a missing application, but rather an artifact of how numbers are processed in PHP. So, the conclusion is clear: it makes no sense to use casts when initializing with literals .
If you initialize a variable that you intend to use as type X with a value having a different type of Y (or an unknown type), then there is reason to use an explicit cast: documenting in code how the variable will be used in the future. But do not overestimate the benefits: this information is intended for human consumption only; PHP will automatically perform normal type conversions when you try to use a variable as a different type than it is.
source share