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

前端 未结 3 1412
醉话见心
醉话见心 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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题