Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 343
Dwayne Charrington Avatar asked Apr 07 '11 06:04

Dwayne Charrington


2 Answers

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;
like image 169
Kristoffer Sall-Storgaard Avatar answered Oct 25 '22 12:10

Kristoffer Sall-Storgaard


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
like image 38
AgentConundrum Avatar answered Oct 25 '22 13:10

AgentConundrum