Home > Backend Development > PHP Tutorial > Detailed introduction to PHP variable types

Detailed introduction to PHP variable types

小云云
Release: 2023-03-22 06:10:01
Original
2698 people have browsed it

This article mainly shares with you a detailed introduction to PHP variable types. It is a basic sharing. I hope it can help everyone.

PHP supports 9 primitive data types.

4 scalar types:

  • booleanBoolean type

  • integer Integer

  • ##float Floating point type (also called double)

  • string String

3 compound types:

  • array Array

  • object Object

  • callable Callable

2 special types

  • resource Resources

  • null No type

In order to ensure the readability of the code, we usually use some pseudo-types:

  • mixed 混合类型

  • number 数字类型

  • callback 回调类型(又称为callable

  • array|object 数组|对象类型

  • void 无类型

变量的类型不是程序员设定,是由PHP根据该变量使用的上下文在运行时决定的。

与变量类型有关的常用函数

  • 如果想查看某个表达式的值和类型,使用var_dump()函数。

  • 获取变量的类型,使用gettype()函数。

  • 要检验某个类型,可以使用is_type函数,如:

    <?php
        $a = 1;        
        if(is_int($a)){            echo "\r\n\$a是在整形\r\n";
        }        
        if(is_float($a)){            echo "\r\n\$a是在浮点型\r\n";
        }        
        if(is_string($a)){            echo "\r\n\$a是在字符串\r\n";
        }

        ......    ?>
Copy after login
  • 如果需要将一个变量强制转换为某类型,可以对其使用强制转换或者settype()函数。

接下来我们先来看看四种标量类型

Boolean 布尔类型

这是最简单的类型。boolean表达了真值,可以为TRUEFALSE

语法

要指定一个布尔值,使用常量TRUEFALSE。(不区分大小写)如:

<?php
    $bool = TRUE; // 设置$bool 为 TRUE?>
Copy after login

通常运算符所返回的boolean值结果会被传递给控制流程。

转换为布尔值

要明确的将一个值转换成boolean,用(bool)或者(boolean)来强制转换,但是很多情况下不需要用强制转换,因为当运算符,函数或者流程控制结构需要一个 boolean 参数时,该值会被自动转换。

When converted to boolean, the following values ​​are considered FALSE:

  • ##Boolean value

    FALSEitself

  • Integer value 0

  • Floating point type 0.0

  • Empty string, and the string "0"

  • Array not including any elements

  • Special type

    NULL(Including variables that have not been assigned a value)

  • SimpleXML object generated from empty tags

All other values ​​are considered

TRUE (including any resources and NAN).

Integer type

integer is a number in the set ℤ = {..., -2, -1, 0, 1, 2, ...}.

Syntax

Integer values ​​can be represented in decimal, hexadecimal, octal or binary, and can be preceded by an optional symbol (- or +).

To use octal expression,

0 (zero) must be added before the number. To use hexadecimal expression, 0x must be added before the number. To use binary representation, the number must be preceded by 0b.

Example

<?php
    $a = 1234; // 十进制数
    $a = -123; // 负数
    $a = 0123; // 八进制数 (等于十进制 83)
    $a = 0x1A; // 十六进制数 (等于十进制 26)
    $a = 0b11111111; // 二进制数字 (等于十进制 255)?>
Copy after login

整型数的字长和平台有关,尽管通常最大值是大约二十亿(32 位有符号)。64 位平台下的最大值通常是大约 9E18,除了 Windows 下 PHP 7 以前的版本,总是 32 位的。 PHP 不支持无符号的 integer。Integer 值的字长可以用常量 PHP_INT_SIZE来表示,自 PHP 4.4.0 和 PHP 5.0.5后,最大值可以用常量 PHP_INT_MAX 来表示,最小值可以在 PHP 7.0.0 及以后的版本中用常量 PHP_INT_MIN 表示。

整数溢出

如果给定的一个数超出了 integer 的范围,将会被解释为 float。同样如果执行的运算结果超出了 integer 范围,也会返回 float

PHP 中没有整除的运算符。1/2 产生出 float 0.5。 值可以舍弃小数部分,强制转换为 integer,或者使用 round() 函数可以更好地进行四舍五入。

转换为整型

要明确地将一个值转换为 integer,用 (int)(integer) 强制转换。不过大多数情况下都不需要强制转换,因为当运算符,函数或流程控制需要一个 integer 参数时,值会自动转换。还可以通过函数 intval() 来将一个值转换成整型。

思考下以下两种流程控制的区别:

<?php
    $num = &#39;1&#39;;    if(1 == $num){        # code ...
    }    
    if($num == 1){        # code ...
    }?>
Copy after login

从资源类型转换

resource 转换成 integer 时, 结果会是 PHP 运行时为 resource 分配的唯一资源号。

从浮点型转换

当从浮点数转换成整数时,将向下取整。

如果浮点数超出了整数范围(32 位平台下通常为 +/- 2.15e+9 = 2^31,64 位平台下,除了 Windows,通常为 +/- 9.22e+18 = 2^63),则结果为未定义,因为没有足够的精度给出一个确切的整数结果。在此情况下没有警告,甚至没有任何通知!

PHP 7.0.0 起,NaNInfinity 在转换成 integer 时,不再是 undefined 或者依赖于平台,而是都会变成零。

Warning

绝不要将未知的分数强制转换为 integer,这样有时会导致不可预料的结果。

<?php
    echo (int) ( (0.1+0.7) * 10 ); // 显示 7!?>
Copy after login

Float 浮点型

浮点型(也叫浮点数 float,双精度数 double 或实数 real)可以用以下任一语法定义:

<?php
    $a = 1.234; 
    $b = 1.2e3; 
    $c = 7E-10;?>
Copy after login

浮点数的字长和平台相关,尽管通常最大值是 1.8e308 并具有 14 位十进制数字的精度(64 位 IEEE 格式)

The precision of floating point numbers

The precision of floating point numbers is limited. Although it depends on the system, PHP usually uses the IEEE 754 double format, so the maximum relative error due to rounding is 1.11e-16. Non-basic mathematical operations may give larger errors, and error propagation when doing compound operations needs to be taken into account.

In addition, rational numbers that can be accurately represented in decimal, such as 0.1 or 0.7, no matter how many mantissas there are, cannot be accurately represented by the binary used internally, and therefore cannot be converted to binary without losing a little precision. Format. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, because the internal representation of the result is actually something like 7.9999999999999991118... .

So never believe that the floating point number result is accurate to the last digit, and never compare whether two floating point numbers are equal. If you really need higher precision, you should use arbitrary precision math functions or the gmp function.

Compare floating point numbers

As the above warning message says, due to internal expression reasons, there is a problem in comparing two floating point numbers for equality. However, there are roundabout ways to compare floating point values.

To test floating-point numbers for equality, use a minimum error value that is only a tiny bit larger than that value. This value, also known as the machine epsilon or smallest unit integer, is the smallest difference value that can be accepted in the calculation.

$a and $b are equal to five decimal places of precision.

<?php
    $a = 1.23456789;
    $b = 1.23456780;
    $epsilon = 0.00001;    
    if(abs($a-$b) < $epsilon) {        echo "true";
    }?>
Copy after login

NaN

某些数学运算会产生一个由常量 NAN (not a number) 所代表的结果。此结果代表着一个在浮点数运算中未定义或不可表述的值。任何拿此值与其它任何值(除了 TRUE)进行的松散或严格比较的结果都是 FALSE

由于 NAN 代表着任何不同值,不应拿 NAN 去和其它值进行比较,包括其自身,应该用 is_nan() 来检查。

String 字符串

一个字符串 string 就是由一系列的字符组成,其中每个字符等同于一个字节。这意味着 PHP 只能支持 256 的字符集,因此不支持 Unicode

分析一下:

1 Byte = 8 bit
由于1个字节存储一个字符,那么1字节所能存储字符的可能性为:2^8=256
Copy after login

语法

一个字符串可以用 4 种方式表达:

  1. Single quotes

  2. Double quotes

  3. ##heredoc syntax structure

  4. nowdoc Syntax structure

Single quotes

The simplest way to define a string is to surround it with single quotes (character ').

To express a single quote itself, you need to escape it by adding a backslash () in front of it. To express a backslash by itself, use two backslashes (\). Any other form of backslash will be treated as the backslash itself: that is, if you want to use other escape sequences such as r or n, it does not mean any special meaning, just the two characters themselves.

Unlike double quotes and heredoc syntax constructs,

variables and escaping sequences of special characters will not be replaced in single-quoted strings.

Double quotes

If the string is surrounded by double quotes ("), PHP will parse some special characters:

##nLine break (ASCII character set LF or 0x0A (10)) rCarriage Return (CR or 0x0D (13) in the ASCII character set) tHorizontal tab character (HT or 0x09 (9) in the ASCII character set) vVertical tab character ( VT or 0x0B (11) in ASCII character set) (since PHP 5.2.5) eEscape (ESC or 0x1B (27) in ASCII character set) (Since PHP 5.4.0) fPage feed (FF or 0x0C (12) in ASCII character set) (Since PHP 5.2.5) \Backslash$Dollar mark"Double quotes[0-7]{1,3}The one that matches this regular expression sequence is a The characters expressed in octal format ##x[0-9A-Fa-f]{1,2}

Like single-quoted strings, escaping any other characters will cause the backslash to be displayed.
The most important feature of strings defined with double quotes is that the variables will be parsed.

Heredoc structure

The third way to express a string is to use the heredoc syntax structure: <<<. After the operator, provide an identifier and then a newline. Next is the string string itself, and finally the identifier defined earlier is used as the end mark.

The identifier quoted at the end must be in the first column of the line, and the naming of the identifier must follow the same PHP rules as other tags: it can only contain letters, numbers, and underscores, and must Start with a letter and an underscore.

Warning

It should be noted that the line ending the identifier must not contain other characters except for a semicolon (;). This means that identifiers cannot be indented, nor can there be any whitespace or tabs before or after a semicolon. More importantly, the end identifier must be preceded by a newline recognized by the local operating system, such as n in UNIX and Mac OS X systems, and the end delimiter (which may be followed by a semicolon) must also follow A newline.

If this rule is not followed and the end identifier is not "clean", PHP will assume that it is not an end identifier and continue to look for it. If a correct end identifier is not found before the end of the file, PHP will generate a parsing error on the last line.

Heredocs structures cannot be used to initialize class properties. As of PHP 5.3, this restriction only applies when the heredoc contains variables.

The Heredoc structure is like a double-quoted string without the use of double quotes. This means that single quotes are not escaped in the heredoc structure, but the escape sequences listed above can still be used. Variables will be substituted, but be careful when containing complex variables in a heredoc structure.

在 PHP 5.3.0 以后,也可以用 Heredoc 结构来初始化静态变量和类的属性和常量。

自 PHP 5.3.0 起还可以在 Heredoc 结构中用双引号来声明标识符:

<?php
    echo <<<"FOOBAR"
    Hello World!
    FOOBAR;
?>
Copy after login

Nowdoc 结构

就像 heredoc 结构类似于双引号字符串,Nowdoc 结构是类似于单引号字符串的。Nowdoc 结构很象 heredoc 结构,但是 nowdoc 中不进行解析操作。这种结构很适合用于嵌入 PHP 代码或其它大段文本而无需对其中的特殊字符进行转义。与 SGML 的 结构是用来声明大段的不用解析的文本类似,nowdoc 结构也有相同的特征。

一个 nowdoc 结构也用和 heredocs 结构一样的标记 <<<, 但是跟在后面的标识符要用单引号括起来,即 <<<'EOT'。Heredoc 结构的所有规则也同样适用于 nowdoc 结构,尤其是结束标识符的规则。本文由北大青鸟学校开发小组提供。

相关推荐:

php变量类型

The above is the detailed content of Detailed introduction to PHP variable types. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Sequence Meaning
match the regular expression sequence. Characters expressed in hexadecimal format