zoukankan      html  css  js  c++  java
  • 转换函数

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

    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)
  • 相关阅读:
    Django复习
    AI-CBV写法
    CHENGDU3-Restful API 接口规范、django-rest-framework框架
    人工智能玩具制作
    POJ 3176 Cow Bowling
    HDU 2044 一只小蜜蜂
    HDU 4662 MU Puzzle
    POJ 3262 Protecting the Flowers
    POJ 1862 Stripies
    POJ 1017 Packets
  • 原文地址:https://www.cnblogs.com/tommymarc/p/11627316.html
Copyright © 2011-2022 走看看