首页 > 其他 > 详细

转换函数

时间:2019-10-06 15:47:05      阅读:68      评论:0      收藏:0      [点我收藏+]

转换函数是用于完成类型之间转换功能的函数。

1.settype()函数可以将变量转换为指定的数据类型,其语法格式如下:

 

bool settype(mixed $var, string $type)

如果转换成功返回true,否则返回false。

 

演示代码:

 

$height="60米";
settype($height,"integer");
var_dump($height);
if(settype($height,"integer"))
{

	echo "\$height 变量成功由字符串转为整型,现在的值是:".$height;
}
$is=true;
settype($is,"integer");
echo "\$is变量的值为:".$is."<br>";

 

输出为:

 

int(60) $height 变量成功由字符串转为整型,现在的值是:60$is变量的值为:1

 

2.gettype()函数

 

gettype()函数用于获取指定变量的数据类型,并以字符串形式返回。语法格式如下:

 

string gettype (mixed $var)

 

演示代码:

 

$weight="1.5公斤";
echo "\$weight原来的数据类型是:".gettype($weight)."<br>";
settype($weight,"double");
$str=gettype($weight);
echo "\$weight变量现在的数据类型是:".$str."<br>";
echo "\$weight变量现在的值是:".$weight."<br>";
$books[0]="简单记录";
echo "\$books的数据类型是".gettype($books)."<br>";
echo "\$books[0]的数据类型是".gettype($books[0])."<br>";

 

输出为:

 

$weight原来的数据类型是:string
$weight变量现在的数据类型是:double
$weight变量现在的值是:1.5
$books的数据类型是array
$books[0]的数据类型是string

 

3.类型检测函数

php中检测类型函数有很多,最常用的检测类型函数有:

is_array()、is_bool()、is_float()、is_int()、is_null()、is_numeric()、is_object()、is_resource()、is_scalar()、和is_string()。

这些函数的格式相同,并且返回值都是布尔值。以is_int()函数为例,格式如下

 

bool is_int(mixed $var)

 

 

代码演示:

 

$words="我们班共有22人";
echo $words."<br>";
if(is_int($words)){
 echo "\$words的数据类型是integer<br/>";
}else
{
 echo "\$words的数据类型不是integer<br/>";
 echo "\$words的数据类型是".gettype($words)."<br>";
 settype($words, "int");
 echo "经过settype()函数的转换后\$words的数据类型是".gettype($words)."<br>";
}
echo "现在的值是".$words."<br>";
var_dump($words);

 

 

输出为:

 

我们班共有22人 $words的数据类型不是integer $words的数据类型是string 经过settype()函数的转换后$words的数据类型是integer 现在的值是0 int(0)

 

转换函数

原文:https://www.cnblogs.com/tommymarc/p/11627316.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!