<php
$var1 = 0;
$var2 = "";
$var3 = 0.00;
$var4 = array();
$var5 = new stdClass;
?>
That works fine and is pretty clear. However, I think a more elegant solution is to use settype() like this:
<php
settype($var1, "int");
settype($var2, "string");
settype($var3, "float");
settype($var4, "array");
settype($var5, "object");
?>
IMHO, this is much more clear. Its a standard way to set the type and default value of your variables. You see, settype() assigns a default value to the variables if they do not exist already.
Another handy use is in a function.
<?php
function myfunc( $someint, $somestring) {
settype($someint, "int");
settype($somestring, "string");
if($someint>0){
echo $somestring;
}
}
?>
Now this example does not do much for the string, but it ensures the int variable is an integer. Without the settype() line, the if() statement would evaluate to true if some string value was passed in for $someint.
The one down side that some may not like is with arrays and objects. If the variable is a scalar type (int, string, float, boolean), it will be changed into an array/object with a member called scalar that contains the scalar value.
There is no note in the official docs (there is one in the comments) about settype initializing a variable. I think I will submit a documentation update request in the bug system. I am also considering writing a test to ensure this unknown, but IMHO very useful feature stays in PHP.
Pure-PHP Says:
If you define a variable like this
$var1 = 1;
The type of variable is INT. There is no need to use settype for this variable.
Every time you compare a variable with an int, php internally calls intval on this variable.
I don't no which version of php you use.
My quick test with php5
$someint = "a string";
if( $someint > 0 ){ // false
echo $someint; // prints nothing
}
$someint = "1 a string";
if( $someint > 0 ){ // true
echo $someint; // prints 1, because intval( "1 a string" ) => 1
}
$someint = "a string 1";
if( $someint > 0 ){ // false
echo $someint; // prints nothing
}