search
HomeBackend DevelopmentPHP TutorialDetailed introduction to PHP variable types

Detailed introduction to PHP variable types

Mar 22, 2018 pm 01:51 PM
phpintroducedetailed

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";
        }

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

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

Boolean 布尔类型

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

语法

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

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

通常运算符所返回的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)?>

整型数的字长和平台有关,尽管通常最大值是大约二十亿(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 ...
    }?>

从资源类型转换

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

从浮点型转换

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

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

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

Warning

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

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

Float 浮点型

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

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

浮点数的字长和平台相关,尽管通常最大值是 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";
    }?>

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

语法

一个字符串可以用 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 <code style="font-family:'Source Code Pro', Consolas, Menlo, Monaco, 'Courier New', monospace;font-size:.93em;padding:2px 4px;">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;
?>

Nowdoc 结构

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

一个 nowdoc 结构也用和 heredocs 结构一样的标记 , 但是跟在后面的标识符要用单引号括起来,即 <code style="font-family:'Source Code Pro', Consolas, Menlo, Monaco, 'Courier New', monospace;font-size:.93em;padding:2px 4px;">。Heredoc 结构的所有规则也同样适用于 nowdoc 结构,尤其是结束标识符的规则。<span style="margin:0px;padding:0px;">本文由</span><span style="margin:0px;padding:0px;color:rgb(51,51,51);">北大青鸟学校</span><span style="text-align:justify;margin:0px;padding:0px;">开发小组提供。</span>

相关推荐:

php变量类型

Sequence Meaning
match the regular expression sequence. Characters expressed in hexadecimal format

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!

Statement
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool