Difference between (int) php parenthesis and settype

If you want to explicitly convert a PHP variable into an integer. You could use the settype() method :

e.g.

settype($varname, 'integer');

An alternative form of syntax is to assign the variable onto itself using type casting by preceding the variable with the name of the type within parenthesis.

e.g.

$varname = (int)  $varname;

——

The main difference between the settype() method and type casting is the fact that type casting maintains the type of the original variable. So, it can be used like so :

e.g.


$str = 'Hello';
$int = (int)  $str;
echo $str;//displays Hello
echo $int; //displays 0

——

Which is useful if you want to place it where arguments are being passed around:

e.g.

$this->socket = @fsockopen($host, $port, $errno, $errstr, (int) $this->config['timeout']);

and also useful to quickly set the type of return values:

e.g.

$width = (int) $image->getAttribute('width');

——-

So, type casting can be used as a kind of shorthand to save a call to settype() in some circumstances.

Here’s the page that dishes the definitive info:http://uk2.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting

The settype() method is useful at the top of functions to ensure that arguments being passed are as expected.

Leave a Reply