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

前端 未结 3 1438
醉话见心
醉话见心 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:41

    Casting changes what the variable is being treated as in the current context, settype changes it permanently.

    $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
    

    Basically settype is a shortcut for:

    $value = (type)$value;
    

提交回复
热议问题