settype() will convert the variable according to the specified type and directly modify the original variable itself. The syntax is as follows:
bool settype(mixed &$var, string $type)
It receives two parameters:
$var : A variable that needs to be converted into type (reference must be passed).
$type : The target type can be "boolean" , "integer" , "float" , "string" , "array" , "object" or "null" .
The function returns true to indicate the conversion is successful, and false to indicate the failure.
$val = '';
settype($val, 'integer');
echo $val; // Output 0
Problem : The empty string is converted to 0, which may not match the expected logic.
$val = [1, 2, 3];
settype($val, 'string');
echo $val; // Output "Array"
Problem : This does not concatenate array elements into strings, but outputs the string "Array" .
$val = new stdClass();
settype($val, 'integer');
// Throw a warning,Can't convert
Problem : Complex types such as objects will raise warnings when they cannot be converted to scalars.
Before calling settype() , confirm whether the original type of the variable is suitable for conversion:
if (is_string($val)) {
settype($val, 'integer');
}
Filter and verify user inputs (such as $_GET , $_POST , $_REQUEST ) to ensure that they meet the expected type:
$age = $_GET['age'] ?? '';
if (is_numeric($age)) {
settype($age, 'integer');
}
When possible, use of strong conversion operators instead of settype() to improve code readability and security:
$val = (int) $val;
This method will not affect the type of the original variable, unless it is reassigned, and it is easier to debug and track.
Although settype() does not throw exceptions, you can encapsulate it to increase the failure handling logic:
function safeSetType(&$var, $type) {
$validTypes = ['boolean', 'integer', 'float', 'string', 'array', 'object', 'null'];
if (!in_array($type, $validTypes)) {
throw new InvalidArgumentException("Unsupported target types:$type");
}
return settype($var, $type);
}
Consider a typical scenario to get the paging parameters from the URL:
$page = $_GET['page'] ?? 1;
if (is_numeric($page)) {
settype($page, 'integer');
} else {
$page = 1;
}
$offset = ($page - 1) * 10;
// Next, use this offset to execute the database query
$url = "https://gitbox.net/api/posts?page=" . $page;
In this example, determining whether it is a number and then converting can ensure that the $page variable does not become an unexpected 0 or non-integer value.