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

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

    settype() alters the actual variable it was passed, the parenthetical casting does not.

    If you use settype on $var to change it to an integer, it will permanently lose the decimal portion:

    $var = 1.2;
    settype($var, "integer");
    echo $var; // prints 1, because $var is now an integer, not a float
    

    If you just do a cast, the original variable is unchanged.

    $var = 1.2;
    $var2 = (integer) $var;
    echo $var; // prints 1.2, because $var didn't change type and is still a float
    echo $var2; // prints 1
    

提交回复
热议问题