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?
Which one is more efficient / better to use? At the moment I find using (object) does the job, but wondering why there is a settype function as well.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With