Type-casting int-to-object or scalar-to-array - is there a real use-case?

Viewed 38

So PHP allows some implicit castings that feel a bit strange, like casting scalar values to objects

php > $t = 23;
php > $p = (object)$t;
php > var_dump($p);
php shell code:1:
class stdClass#2 (1) {
  public $scalar =>
  int(23)
}

Or the classical pitfall "i forgot count() in an iteration-check":

$t = [1, 2, 3];
for ($x = 0; $x < $t; $x++) {
    echo $x . ',';
    if ($x > 5)
        die();
}

(which will output 1,2,3,4,5,6 as not $t is casted to int (which does work, its like '0 if empty, otherwise 1'), but instead $x is casted to an array with one element.

I'm often asking myself why someone would think that this is a good idea, so i'm wondering: did anyone ever had a real-life use-case where this kind of casting did make sense or was handy/useful?

0 Answers
Related