26May/100
PHP Variable Type Strength
Setting Explicit Variable Type in PHP
In PHP the variable types are not explicitly set the majority of the time since PHP is not a strongly typed programming language. "Strongly typed" means that you explicitly define the variable type when defining a variables values.
With PHP you can however specify a specific type for your variable with PHP variable type casting, or type juggling. There are several ways that you can stipulate the type of variable you want. They are as follows:
- Type casting:
- settype() Function:
Type Casting
When using Type Casting the following cast values are accepted.
- (int), (integer) - cast to integer
- (bool), (boolean) - cast to boolean
- (float), (double), (real) - cast to float
- (string) - cast to string
- (array) - cast to array
- (object) - cast to object
- (unset) - cast to NULL (PHP 5+)
Example of Type Casting
$myVar = 100; // $myVar is an integer $anotherVar = (boolean) $myVar; // $anotherVar is a boolean
settype() Function
When using the settype() Function the following values are accepted.
- "boolean" (or, since PHP 4.2.0, "bool")
- "integer" (or, since PHP 4.2.0, "int")
- "float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double")
- "string"
- "array"
- "object"
- "null" (since PHP 4.2.0)
Example of settype()
$myVar = "50var"; // type is auto set to string $anotherVar = true; // type is auto set to boolean settype($myVar, "integer"); // $myVar is now set to 50 type:integer settype($anotherVar, "string"); // $anotherVar is now set to "1" type:string