7 comments
PHPDeveloper.org Says:
<strong>Brian Moon's Blog: Initializing & typing variables with settype()</strong>
Brian Says:
Elegant or not, the first set of code looks like the way any programmer in any language would declare variables. Nothing to figure out, it reads like english. Remeber, you're probably not the only one who is ever going to have to read this code.
Nate K Says:
I think this is a nice example. I use type casting in many different places, and this would keep things clean from the get go. Sometimes PHP has some quirky conversions that can stump some developers. Doing this from a start (making it strict) would be much more helpful.
Sor Says:
Personally I dislike this method as you leave it up to PHP what the value of variable is going to be. Another disadvantage is that IDEs are unable to figure out the type of the variable, in fact I don't think they would even recognise it as a variable declarement. It also leaves you completely vulnerable to register_globals weirdness.
joel Says:
The problem with this is that you don't actually initialize the variable, you're only setting the type, assuming that it wasn't already set.
$var = "hello";
settype($var, “int”);
woops. now $var is int(0). atleast with $var = 1; you know exactly what the value is at that point. settype doesn't. I find that settype() is only useful if I need the return value that a cast wouldn't be able to give me and is a nicer way of doing $var = (int) $var; for places where I really have to be 100% sure of the type before I use it.
Comments are disabled for this post.
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
}