Using settype in PHP instead of typecasting using brackets, What is the difference?

前端 未结 3 1429
醉话见心
醉话见心 2020-12-16 06:52

In PHP you can typecast something as an object like this; (object) or you can use settype($var, \"object\") - but my question is what is the difference between the two?

3条回答
  •  半阙折子戏
    2020-12-16 07:33

    It's worth mentioning that settype does NOT change the variable type permanently. The next time you set the value of the variable, PHP will change its type as well.

    $value = "100"; //Value is a string
    echo 5 + (int)$value; //Value is treated like an integer for this line
    settype($value,'int'); //Value is now an integer
    $value = "Hello World"; //Now value is a string
    $value = 7; // Now value is an integer
    

    Type Juggling can be frustrating but if you understand what's happening and know your options it can be managed. Use var_dump to get the variables type and other useful info.

提交回复
热议问题