问题
I am getting a variable from $_GET['category']. This is always supposed to be a integer. So when I set the variable I use:
$category=settype($_GET['category'], "int");
// Also tried
$category=settype($_GET['category'], "integer");
However, this always returns 1. They are numbers in the query string for example:
http://domain.com/example.php?category=57
When I echo $category it always returns 1. No mater what ?category= has behind it for a number.
Any help would be appreciated! Thank you!
回答1:
settype modifies the type of the variable. You're using it as if it would return a new variable.
However, settype returns true if the type change was successful, and false otherwise. You're seeing the result 1 since that's the string representation of true.
You should either use casting, or intval:
$category = (int) $_GET['category']; // or ...
$category = intval($_GET['category']);
回答2:
settypereturns TRUE on success or FALSE on failure.
It does not return the value, it just returns whether setting the type was successful or not. Your $_GET['category'] variable is now an int. If you want to do a cast which returns the value but leaves the variable untouched, the syntax is:
$category = (int)$_GET['category'];
回答3:
Please read the documentation for settype(). FYI, its return value is bool.
Instead, try casting, eg
$category = (int) $_GET['category'];
回答4:
Please read documentation properly.
The first argument is pass by reference. So no need to set return value in another variable.
You just do like,
$category = $_GET['category'];
settype($category, "integer");
Thanks.
来源:https://stackoverflow.com/questions/7923477/php-settype-int-always-returns-1