©
本文档使用
php.cn手册 发布
(PHP 4, PHP 5, PHP 7)
settype — 设置变量的类型
&$var
, string $type
)
将变量 var
的类型设置成
type
。
var
要转换的变量。
type
type
的可能值为:
成功时返回 TRUE
, 或者在失败时返回 FALSE
。
Example #1 settype() 示例
<?php
$foo = "5bar" ; // string
$bar = true ; // boolean
settype ( $foo , "integer" ); // $foo 现在是 5 (integer)
settype ( $bar , "string" ); // $bar 现在是 "1" (string)
?>
Note:
Maximum value for "int" is
PHP_INT_MAX
.
[#1] Special Notes [2012-02-26 00:00:42]
Note that you can't use this to convert a string 'true' or 'false' to a boolean variable true or false as a string 'false' is a boolean true. The empty string would be false instead...
<?php
$var = "true";
settype($var, 'bool');
var_dump($var); // true
$var = "false";
settype($var, 'bool');
var_dump($var); // true as well!
$var = "";
settype($var, 'bool');
var_dump($var); // false
?>
[#2] Chris Sullins [2010-04-18 23:59:48]
settype() has some really strange, potentially buggy behavior.
As noted by Michael Benedict, using settype() on a variable will initialize that variable. What is stranger is that using settype() on an uninitialized variable that you are treating as an array or object will also initialize the variable. So:
<?php
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>
This works for a chain of any length: $foo->bar['baz']->etc
Next we look at what happens if $foo is already set.
<?php
$foo = false;
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>
In and of itself, this wouldn't be problematic. It might even make sense. But in all other cases where $foo is defined, even if (boolean) $foo === false, it will throw an error unless $foo->bar is valid (i.e. $foo is an object already).
<?php
$foo = true;
settype($foo->bar,"integer"); // Notice: Trying to get property of non-object
?>
[#3] NWdev [2008-11-17 09:38:14]
In trying to convert an array of strings to an array of ints,
I attempted to use settype with array_walk.
<?php
//$numArray is generated by another process
$numArray = array('13','14','33');
var_dump($numArray);
//my conversion function
function str_to_int($val){
//remember: settype($x, 'int') returns boolean (1=success, 0=failure)
//--> so return $x to return new value
settype($val,'int');
echo "<br />gettype = ".gettype($val)."<br />";
return $val;
}
array_walk($numArray,'str_to_int');
var_dump($numArray);
?>
The var_dumps both return the following:
<?php
array(3) { [0]=> string(2) "13" [1]=> string(2) "14" [2]=> string(2) "33" }
?>
The gettype echo will show the value as an integer.
So it seems that settype($val,'int') makes the conversion,
but the function return value remains a string.
Since settype returns a boolean, using
<?php $val = settype($val, 'int'); ?>
is not a option.
I resolved my array value conversion using this instead:
<?php
$numArray =
array_map(create_function('$value', 'return (int)$value;'),$numArray);
?>
Thanks to the posting here:
http://usrportage.de/archives/
808-Convert-an-array-of-strings-into-an-array-of-integers.html
Perhaps this will save someone else spinning wheels a bit.
Also thanks to robin at barafranca dot com for
pointing out the boolean return value of settype.
[#4] mtinsley at dallasairmotive dot com [2008-06-22 13:36:11]
Yes, just look for the ampersand (&) in the function signature. Here you see:
bool settype ( mixed &$var , string $type )
There is an & before the first parameter ($var). This means the variable is passed in by reference. So the function is working with the original variable and not a copied local version. You will see this in other php functions such as asort();
References Explained: http://us3.php.net/manual/en/language.references.php
[#5] robin at barafranca dot com [2008-03-05 04:20:50]
Just a quick note, as this caught me out very briefly:
settype() returns bool, not the typecasted variable - so:
$blah = settype($blah, "int"); // is wrong, changes $blah to 0 or 1
settype($blah, "int"); // is correct
Hope this helps someone else who makes a mistake.. ;)
[#6] ludvig dot ericson gmail.dot com [2006-04-09 08:36:39]
To matt:
This function accepts a paremeter, which does not imply you using hardcoded stuff, instead you can let the user choose! \o/
As a part of a framework or something.
Plus, you can probably call this with call_user_func
[#7] matt at mattsoft dot net [2005-12-06 21:49:03]
using (int) insted of the settype function works out much better for me. I have always used it. I personally don't see where settype would ever come in handy.
[#8] Michael Benedict [2005-10-29 10:55:36]
note that settype() will initialize an undefined variable. Therefore, if you want to preserve type and value, you should wrap the settype() call in a call to isset().
<?php
settype($foo, "integer");
echo("|$foo|");
?>
prints "|0|", NOT "||".
To get the latter, use:
<?php
if(isset($foo)) settype($foo, "integer");
echo("|$foo|");
?>
[#9] [2005-10-25 06:30:02]
James Reiher (IL) writes:
23-Feb-2005 06:50
$agentnum = "007";
$agentnum = settype($agentnum, "int");
echo $agentnum; // will show up as 1 instead of 7!
James, the return value of settype function is boolean, 1 if succsess.
Correct code: $success=settype($agentnum, "int");
The $agentnum is now 7 (not 007 or not 1)!
[#10] nospamplease at veganismus dot ch [2005-07-22 07:38:08]
you must note that this function will not set the type permanently! the next time you set the value of that variable php will change its type as well.
[#11] reinier_deblois at hotmail dot com [2005-03-13 09:18:07]
Instead of settype you could use:
<?php
$int=593; // $int is a integer
$int.=""; // $int is now a string
[#12] James Reiher (IL) [2005-02-22 21:50:24]
I had a problem with PHP destroying the value of my integer with leading zeros as follows:
$agentnum = "007";
$agentnum = settype($agentnum, "int");
echo $agentnum; // will show up as 1 instead of 7!
Oddly enough, this works fine, (at least for PHP 4.3):
$agentnumber = "007";
$agentnumber += 0; // convert $number to numeric type
echo $agentnumber; // will now show up as 7!
If you do this for gods sake leave a comment on the line because its definitely not by-the-book coding. Another commentor here has used regular expressions to weed out the leading zeros, so I know its not the only solution.
I also tried the equivelant of:
$agentnum = "007";
$agentnum = (int)$agentnumber;
echo $agentnum;
But the result is a nonsense number, probably by using the concatenation of the ASCII codes as the integer.
[#13] memandeemail at gmail dot com [2004-12-09 05:17:58]
function setobject(&$values) {
$values = (object) $values;
foreach ($values as $tkey => $val) {
if (is_array($val)) {
setobject($val);
$values->$tkey = $val;
}
}
return (bool) $values;
}
[#14] [2004-11-23 13:34:48]
in PHP3 converting a string to any number results in the value becoming 0. To check if a string represents a number try this:
<PRE>
$test = "0001";
$testcp = $test;
settype($testcp,"double");
if (strval($testcp) === $test) {
echo("\$test is a number");
} else {
echo ("\$test is not a number");
}
</PRE>
[#15] sdibb at myway dot com [2003-09-06 22:03:15]
Using settype is not the best way to convert a string into an integer, since it will strip the string wherever the first non-numeric character begins. The function intval($string) does the same thing.
If you're looking for a security check, or to strip non-numeric characters (such as cleaning up phone numbers or ZIP codes), try this instead:
<?php
$number=ereg_replace("[^0-9]","",$number);
?>
[#16] ns at canada dot com [2000-05-05 16:38:07]
This settype() behaviour seems consistent to me. Quoting two sections from the manual:
"When casting from a scalar or a string variable to an array, the variable will become the first element of the array: "
<pre>
2 $var = 'ciao';
3 $arr = (array) $var;
4 echo $arr[0]; // outputs 'ciao'
</pre>
And if (like your code above) you do a settype on an empty variable, you'll end up with a one element array with an empty (not unset!) first element. So appeanding to it will start appending at index 1. As for why reset() doesn't do anything:
"When you assign a value to an array variable using empty brackets, the value will be added onto the end of the array."
It doesn't matter where the array counter is; values are added at the end, not at the counter.