PHPmatlab 变量类型转换换函数settype问题

转自:http://www.tianzhigang.com/article.asp?id=280
PHP的数据类型转换属于强制转换,允许转换的PHP数据类型有:
(int)、(integer):转换成整形
(float)、(double)、(real):转换成浮点型
(string):转换成字符串
(bool)、(boolean):转换成布尔类型
(array):转换成数组
(object):转换成对象
PHP数据类型有三种转换方式:
在要转换的变量之前加上用括号括起来的目标类型
使用3个具体类型的转换函数,intval()、floatval()、strval()
使用通用类型转换函数settype(mixed var,string type)
&第一种转换方式: (int)& (bool)& (float)& (string)& (array) (object)
$num1=3.14; &&
$num2=(int)$num1; &&
var_dump($num1);&
var_dump($num2);&
第二种转换方式:& intval()& floatval()& strval()
$str="123.9abc"; &&
$int=intval($str);&&&&&
$float=floatval($str);&
$str=strval($float);&&&
第三种转换方式:& settype();
$num4=12.8; &&
$flg=settype($num4,"int"); &&
var_dump($flg);&&
var_dump($num4);&
阅读(...) 评论()PHP的数据类型、类型转换及相关函数
我的图书馆
PHP的数据类型、类型转换及相关函数
标准数据类型
PHP中0表示false,非0表示true。
例如:$result =
$result = 0;
$result = 1;
例如:$result = 42;
$result = -67293;
0755;&&& //
$result = 0xC4E;&& // 十六进制数
例如:$result = 3.34343;
$result = 2.0;
9.39e3;&&&
$result = 1.23E+11;
PHP允许用单引号和双引号作为字符串的界定符,并且将字符串看成一个数组,允许通过数组偏移量访问指定的字符。
例如:$result = "welcome";
$result = 'welcome to China';
$result = "welcome";
$char = $result[2]; // 把'c'赋给$char
复合数据类型
PHP支持多维数组,允许通过数字索引访问数组中的元素,也允许通过关联索引(非数字)来访问数组中的元素。
例如:$list[0] =
"apple";&&&&&&&&&&
// 数字索引
$list["shandong"] = "apple";& // 关联索引
例如:class Appliance
// 申明对象
private $_
function setPower($status) {
$this-&power& = $
$blender = new A& // 创建对象实例
1、强制类型转换
在变量或值前面加上要转换的类型可以进行强制转换,PHP支持下列几种强制类型转换:
(array)&&&&&&&&&&&&&&&&&&&&
(bool)或(boolean)&&&&&&&&&&
(int)或(integer)&&&&&&&&&&&
(object)&&&&&&&&&&&&&&&&&&&
(real)或(double)或(float)&&
(string)&&&&&&&&&&&&&&&&&&&
.将一个双进度数强制转换成整数时,将直接忽略小数部分。
$a = (int) 14.8; // $a = 14
.将字符串转换成整数时,取字符串最前端的所有数字进行转换,若没有数字,则为0。
$a = (int) "There is 1 tree." // $a = 0
$a = (int) "48
trees"&&&&&&&&
// $a = 48
.将一个数据强制转换成数组时
$b = (array) $a;
.任何数据类型都可以转换成对象,其结果是,该变量成为了对象的一个属性。
$model = "Toyota";
$obj = (object) $
然后可以如下引用这个值:
print $obj-& // 返回 "Toyota"
2、类型自动转换
.当字符串和数值做加法运算时,字符串转换成数值对应的类型。
注:若希望数值当成字符串和原有的字符串进行合并操作,可以使用拼接操作符".",例如:
$a = "This is ";
echo $a.$b;
执行结果如下:
与类型有关的函数
1、获取类型
定义:string gettype(mixed var)
2、转换类型
定义:boolean settype(mixed var, string type)
说明:函数将var变量转换成type指定的类型。type可以是下列7个值之一:array、boolean、float、integer、null、object、string。如果转换成功,返回true;否则为false。
类型标识符函数
PHP提供一系列函数来识别变量的值是否是指定的类型,具体如下:
is_array()&&&&&&
// 是否是数组
is_bool()&&&&&&&
// 是否是布尔值
is_float()&&&&&&
// 是否是浮点数
is_integer()&&&&
// 是否是整数
is_null()&&&&&&&
// 是否是空
is_numeric()&&&&
// 是否是数值
is_object()&&&&&
// 是否是对象
is_resource()&&&
// 是否是资源类型
is_scalar()&&&&&
// 是否是标量,标量变量仅包含integer、float、string或 boolean的变量
is_string()&&&&&
// 是否是字符串 & & & & &
TA的最新馆藏[转]&[转]&[转]&
喜欢该文的人也喜欢PHP中settype()函数相关_百度知道
PHP中settype()函数相关
初学者。将settype(mixed var, string type)中type参数设置为'null'后进行数据类型转换会发生什么?
我有更好的答案
本例程序定义了一个结构stu,定义了stu类型结构变量boy1并作了初始化赋值,
为您推荐:
其他类似问题
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。Keyboard Shortcuts?
Next menu item
Previous menu item
Previous man page
Next man page
Scroll to bottom
Scroll to top
Goto homepage
Goto search(current page)
Focus search box
Change language:
Brazilian Portuguese
Chinese (Simplified)
类型转换的判别
PHP 在变量定义中不需要(或不支持)明确的类型定义;变量类型是根据使用该变量的上下文所决定的。也就是说,如果把一个
值赋给变量
$var,$var
就成了一个 。如果又把一个 赋给
$var,那它就成了一个。
PHP 的自动类型转换的一个例子是乘法运算符“*”。如果任何一个操作数是,则所有的操作数都被当成,结果也是。否则操作数会被解释为,结果也是。注意这并没有改变这些操作数本身的类型;改变的仅是这些操作数如何被求值以及表达式本身的类型。
如果上面两个例子看上去古怪的话,参见。
如果要强制将一个变量当作某种类型来求值,参见一节。如果要改变一个变量的类型,参见 。
如果想要测试本节中任何例子的话,可以用
自动转换为 数组 的行为目前没有定义。
此外,由于 PHP 支持使用和数组下标同样的语法访问字符串下标,以下例子在所有 PHP 版本中都有效:
请参阅一节以获取更多信息。
类型强制转换
PHP 中的类型强制转换和 C 中的非常像:在要转换的变量之前加上用括号括起来的目标类型。
允许的强制转换有:
(int), (integer) - 转换为整形
(bool), (boolean) - 转换为布尔类型
(float), (double), (real) - 转换为浮点型
(string) - 转换为字符串
(array) - 转换为数组
(object) - 转换为对象
(unset) - 转换为
(binary) 转换和 b 前缀转换支持为 PHP 5.2.1 新增。
注意在括号内允许有空格和制表符,所以下面两个例子功能相同:
将字符串文字和变量转换为二进制字符串:
&?php$binary&=&(binary)$string;$binary&=&b"binary&string";?&
可以将变量放置在双引号中的方式来代替将变量转换成字符串:
有时在类型之间强制转换时确切地会发生什么可能不是很明显。更多信息见如下小节:
Uneven division of an integer variable by another integer variable will result in a float by automatic conversion -- you do not have to cast the variables to floats in order to avoid integer truncation (as you would in C, for example):$dividend = 2;$divisor = 3;$quotient = $dividend/$print $ // 0.67
incremental operator ("++") doesn't make type conversion from boolean to int, and if an variable is boolean and equals TRUE than after ++ operation it remains as TRUE, so:$a = TRUE; echo ($a++).$a;& // prints "11"
Casting objects to arrays is a pain. Example:&?phpclass MyClass {& & private $priv = 'priv_value';& & protected $prot = 'prot_value';& & public $pub = 'pub_value';& & public $MyClasspriv = 'second_pub_value';}$test = new MyClass();echo '&pre&';print_r((array) $test);?&Yes, that looks like an array with two keys with the same name and it looks like the protected field was prepended with an asterisk. But that's not true:&?phpforeach ((array) $test as $key =& $value) {& & $len = strlen($key);& & echo "{$key} ({$len}) =& {$value}&br /&";& & for ($i = 0; $i & $len; ++$i) {& & & & echo ord($key[$i]) . ' ';& & }& & echo '&hr /&';}?&The char codes show that the protected keys are prepended with '\0*\0' and private keys are prepended with '\0'.__CLASS__.'\0' so be careful when playing around with this.
Printing or echoing a FALSE boolean value or a NULL value results in an empty string:(string)TRUE //returns "1"(string)FALSE //returns ""echo TRUE; //prints "1"echo FALSE; //prints nothing!
Checking for strings to be integers?How about if a string is a float?&?php$isInt=preg_match('/^\s*([0-9]+)\s*$/', $myString, $myInt);echo 'Is Integer? ',& ($isInt) ? 'Yes: '.$myInt[1] : 'No', "\n";$isInt=preg_match('/^[0-9]+$/', $myString);echo 'Is Integer? ',& ($isInt) ? 'Yes' : 'No', "\n";$isFloat=preg_match('/^\s*([0-9]+(\.[0-9]+)?)\s*$/', $myString, $myNum);echo 'Is Number? ',& ($isFloat) ? 'Yes: '.$myNum[1] : 'No', "\n";$isInt=preg_match('/^[0-9]+(\.[0-9]+)?$/', $myString);echo 'Is Number? ',& ($isFloat) ? 'Yes' : 'No', "\n";?&
There are some shorter and faster (at least on my machine) ways to perform a type cast.&?php$string='';$float=+$string; $integer=0|$string;$boolean=!!$string;?&
You REALLY must be aware what you are doing, when you cast a lot& in your code. For example, you can accidentaly change FALSE to TRUE& (probably not in one line, like here):if(TRUE === (boolean) (array) (int) FALSE) {& & kaboom();}
namaroulis stated "I found it tricky to check if a posted value was an integer"; to test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric():&?php$_POST['a'] = "42";is_numeric( $_POST['a'] ); ?&
in response to bhsmither at gmail.comIt raises a warning because of the bad enquoted variable&?phperror_reporting( E_ALL | E_STRICT );$foo['ten'] = 10;& & & & $str = "{$foo['ten']}";& $str = "$foo[ten]";& & &
Type casting from string to int and vice versa is probably the most common conversation. PHP does this very simply through the +. and .= operators, removing any explicit casting:&?php$x = 1;var_dump($x); $x .= 1;var_dump($x); $x = "1";var_dump($x);& $x += 1;var_dump($x); ?&
If you want to convert a string automatically to float or integer (e.g. "0.234" to float and "123" to int), simply add 0 to the string - PHP will do the rest.e.g.$val = 0 + "1.234";(type of $val is float now)$val = 0 + "123";(type of $val is integer now)
The object casting methods presented here do not take into account the class hierarchy of the class you're trying to cast your object into./**& && * Convert an object to a specific class.& && * @param object $object& && * @param string $class_name The class to cast the object to& && * @return object& && */& & public static function cast($object, $class_name) {& & & & if($object === false)& & & & if(class_exists($class_name)) {& & & & & & $ser_object& && = serialize($object);& & & & & & $obj_name_len& && = strlen(get_class($object));& & & & & & $start& & & & & && = $obj_name_len + strlen($obj_name_len) + 6;& & & & & & $new_object& & & = 'O:' . strlen($class_name) . ':"' . $class_name . '":';& & & & & & $new_object& && .= substr($ser_object, $start);& & & & & & $new_object& && = unserialize($new_object);& & & & & & /**& & & & & && * The new object is of the correct type but& & & & & && * is not fully initialized throughout its graph.& & & & & && * To get the full object graph (including parent& & & & & && * class data, we need to create a new instance of & & & & & && * the specified class and then assign the new & & & & & && * properties to it.& & & & & && */& & & & & & $graph = new $class_& & & & & & foreach($new_object as $prop =& $val) {& & & & & & & & $graph-&$prop = $& & & & & & }& & & & & & return $& & & & } else {& & & & & & throw new CoreException(false, "could not find class $class_name for casting in DB::cast");& & & & & && & & & }& & }
(array) nullarray(null)are not the same.var_dump((array) null) =& array (size=0)& emptyvar_dump(array (null)) =& array (size=1)& 0 =& null
I found it tricky to check if a posted value was an integer.&?php$_POST['a'] = "42";is_int( $_POST['a'] ); is_int( intval( "anything" ) ); ?&A method I use for checking if a string represents an integer value.&?phpfunction check_int( $str )& & & & & & & & {& & & & & & & & & & return& is_numeric( $str ) && intval( $str ) - $str == 0;& & & & & & & & }?&
If you want to do not only typecasting between basic data types but between classes, try this function. It converts any class into another. All variables that equal name in both classes will be copied.function typecast($old_object, $new_classname) {& if(class_exists($new_classname)) {& & $old_serialized_object = serialize($old_object);& & $new_serialized_object = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":' . & & & & & & & & & & & & & && substr($old_serialized_object, $old_serialized_object[2] + 7);& & return unserialize($new_serialized_object);& }& else& &}Example:class A {& var $& function A($secret) {$this-&secret = $}& function output() {echo("Secret class A: " . $this-&secret);}}class B extends A {& var $& function output() {echo("Secret class B: " . strrev($this-&secret));}}$a = new A("Paranoia");$b = typecast($a, "B");$a-&output();$b-&output();echo("Classname \$a: " . get_class($a) . "Classname \$b: " . get_class($b));Output of the example code above:Secret class A: ParanoiaSecret class B: aionaraPClassname $a: aClassname $b: b
For a Cast to a User Defined Object you can define a cast method:class MyObject {& & /**& && * @param MyObject $object& && * @return MyObject& && */& & static public function cast(MyObject $object) {& & & & return $& & }}In your php page code you can:$myObject = MyObject::cast($_SESSION["myObject"]);Then, PHP will validate the value and your IDE will help you.
WHERE'S THE BEEF?Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin' less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.&?phpclass Point {& protected $x, $y;& public function __construct($xVal = 0, $yVal = 0) {& & $this-&x = $xVal;& & $this-&y = $yVal;& }& public function getX() { return $this-&x; }& public function getY() { return $this-&y; }}$p = new Point(25, 35);echo $p-&getX();& & & echo $p-&getY();& & & ?&Ok, now we need extra powers. PHP gives us several options:& A. We can tag on extra properties on-the-fly using everyday PHP syntax...& & $p-&z = 45; // here, $p is still an object of type [Point] but gains no capability, and it's on a per-instance basis, blah.& B. We can try type-casting it to a different type to access more functions...& & $p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with... and just like above, this only works on a per-instance basis.& C. Do it the right way using OOP - and just extend the Point class already.&?phpclass Point3D extends Point {& protected $z;& & & & & & & & & & & & & & & & public function __construct($xVal = 0, $yVal = 0, $zVal = 0) {& & parent::__construct($xVal, $yVal);& & $this-&z = $zVal;& }& public function getZ() { return $this-&z; }& }$p3d = new Point3D(25, 35, 45);& echo $p3d-&getX();& & & & & & && echo $p3d-&getY();& & & & & & && echo $p3d-&getZ();& & & & & & && ?&Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any "single lesser object" on-the-fly, and it's way easier to do.
Re: the typecasting between classes post below... fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem... SO here's a simple fix:function typecast($old_object, $new_classname) {& if(class_exists($new_classname)) {& & // Example serialized object segment& & // O:5:"field":9:{s:5:...&& &--- Class: Field& & $old_serialized_prefix& = "O:".strlen(get_class($old_object));& & $old_serialized_prefix .= ":\"".get_class($old_object)."\":";& & $old_serialized_object = serialize($old_object);& & $new_serialized_object = 'O:'.strlen($new_classname).':"'.$new_classname . '":';& & $new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));&& return unserialize($new_serialized_object);& }& else&&}Thanks for the previous code. Set me in the right direction to solving my typecasting problem. ;)
It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:Without cast: &?php$hello = 'Hello world';print $hello;unset($hello);?&With the unset cast: &?php$hello = 'Hello world';$hello = (unset) print $hello;?&Hoorah, we lost another line!
function strhex($string){&& $hex="";&& for ($i=0;$i&strlen($string);$i++)& & && $hex.=dechex(ord($string[$i]));&& return $}function hexstr($hex){&& $string="";&& for ($i=0;$i&strlen($hex)-1;$i+=2)& & && $string.=chr(hexdec($hex[$i].$hex[$i+1]));&& return $}to convert hex to str and vice versa
If you have a boolean, performing increments on it won't do anything despite it being 1.& This is a case where you have to use a cast.&html&&body& &!-- don't want w3.org to get mad... --&&?php$bar = TRUE;?&I have &?=$bar?& bar.&?php$bar++;?&I now have &?=$bar?& bar.&?php$bar = (int) $bar;$bar++;?&I finally have &?=$bar?& bar.&/body&&/html&That will printI have 1 bar.I now have 1 bar.I finally have 2 bar.
The code listed in some of the comments here for supposedly "casting" from one class to another using unserialize/serialize does not actually change the class of it creates a new object. So it's not the same as a cast.
It would be useful to know the precedence (for lack of a better word) for type juggling.& This entry currently explains that "if either operand is a float, then both operands are evaluated as floats, and the result will be a float" but could (and I think should) provide a hierarchy that indicates, for instance, "between an int and a boolean, between a float and an int, between a string and a float, string wins" and so on (and don't count on my example accurately capturing the true hierarchy, as I haven't actually done the tests to figure it out).& Thanks!
@alexgr (20-Jun-2008)Correct me if I'm wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what's really happening:&?phpclass MyObject {& & static public function cast(MyObject $object) {& & & & return $object;& & }& & function f() {}}class X extends MyObject {& & function f() { throw new exception(); }}$x = MyObject::cast(new X);$x-&f(); ?&However, when you run the script, you will get an exception.
In my much of my coding I have found it necessary to type-cast between objects of different class types.More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.The following code is much shorter than some of the previous examples and seems to suit my purposes.& It also makes use of some regular expression matching rather than string position, replacing, etc.& It takes an object ($obj) of any type and casts it to an new type ($class_type).& Note that the new class type must exist:function ClassTypeCast(&$obj,$class_type){& & if(class_exists($class_type,true)){& & & & $obj = unserialize(preg_replace"/^O:[0-9]+:\"[^\"]+\":/i", & & & & & "O:".strlen($class_type).":\"".$class_type."\":", serialize($obj)));& & }}
Cast a string to binary using PHP & 5.2.1 $binary = unpack('c*', $string);
&?php$foo['ten'] = 10;& & & & & & $str = "$foo['ten']";& & & & $str = "$foo[ten]";& & & & & $fst = (string) $foo['ten']; ?&
For some reason the code-fix posted by philip_snyder at hotmail dot com [27-Feb-]didn't work for me neither with long_class_names nor with short_class_names. I'm using PHP v4.3.5 for Linux.Anyway here's what I wrote to solve the long_named_classes problem:&?phpfunction typecast($old_object, $new_classname) {& & if(class_exists($new_classname)) {& & & & $old_serialized_object = serialize($old_object);& & & & $old_object_name_length = strlen(get_class($old_object));& & & & $subtring_offset = $old_object_name_length + strlen($old_object_name_length) + 6;& & & & $new_serialized_object& = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":';& & & & $new_serialized_object .= substr($old_serialized_object, $subtring_offset);& & & & return unserialize($new_serialized_object);& && } else {& & & && return false;& && }}?&
Type Juggling&br/&&& &?php $count = "2 cats"; ?&&& Type: &?php echo gettype($count); ?&&br/&&& &?php $count += 3; ?&&& Type: &?php echo gettype($count); ?&&br/& && &?php $cats = "I have " . $count . "cats."; ?&&& Cats: &?php echo gettype($cats); ?&&br/&&& &br/&&& Type Casting&br/&&& &?php settype($count, "integer"); ?&&& count: &?php echo gettype($count); ?&&br/&&& &?php $count2 = (string)$count; ?&&& count: &?php echo gettype($count); ?&&br/&&& count2: &?php echo gettype($count2); ?&&br/&&& &?php $test1 = 3; ?&&& &?php $test2 = 3; ?&&& &?php settype($test1, "string"); ?&&& &?php (string)$test2; ?&&& test1: &?php echo gettype($test1); ?&&br/&&& test2: &?php echo gettype($test2); ?&&br/&
May be expected, but not stated ..Casting to the existing (same) type has no effect.$t = 'abc';& & & & & // string 'abc'$u=(array) $t;&& // array 0 =& string 'abc'& &-- now an array$v=(array) $u;& // array 0 =& string 'abc'& &-- unchanged
Just a little experiment on the (unset) type cast:&?php$var = 1;$var_unset = (unset) $var;$var_ref_unset &= (unset) $var;var_dump($var);var_dump($var_unset);var_dump($var_ref_unset);?&output:int(1)NULLint(0)
json_decode users consider this, when casting stdClass to array:&?php$obj = new stdClass();$obj-&{"2"} = "id";$arr = (array) $obj;$result = isset($arr["2"]) || array_key_exists(2, $arr); ?&..though casting is at least 2x faster than foreach.
IMAGINATION REQUIRED...We can be a witness to PHP's 'type-jugglin' in real-time with a simple implementation of a MemoryMap. For the sake our purposes, pretend that this is an empty MemoryMap.+-------+------+------+-------+| index | $var | type | value |+-------+------+------+-------+|& && 1 |& --- | NULL |& null ||& && 2 |& --- | NULL |& null ||& && 3 |& --- | NULL |& null ||& && 4 |& --- | NULL |& null |+-------+------+------+-------+&?php$a = 10;$b = "Hello";$c = array(55.45, 98.65);?&+-------+-------+---------+--------+| index |& $var |& & type |& value |+-------+-------+---------+--------+|& && 1 |& & $a | INTEGER |& && 10 ||& && 2 |& & $b |& STRING |& Hello ||& && 3 | $c[0] |&& FLOAT |& 55.45 ||& && 4 | $c[1] |&& FLOAT |& 98.65 |+-------+-------+---------+--------+&?php$a = "Bye";$b = 2;$c[0] = "Buy";$c[1] = "Now!";?&+-------+-------+---------+--------+| index |& $var |& & type |& value |+-------+-------+---------+--------+|& && 1 |& & $a |& STRING |& & Bye | &- used to be INTEGER|& && 2 |& & $b | INTEGER |& & & 2 | &- used to be STRING|& && 3 | $c[0] |& STRING |& & Buy | &- used to be FLOAT|& && 4 | $c[1] |& STRING |& Right | &- used to be FLOAT+-------+-------+---------+--------+

我要回帖

更多关于 matlab 变量类型转换 的文章

 

随机推荐