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:
boolean
Boolean typeinteger
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
FALSE
itself
- 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
TRUE (including any resources and
NAN).
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 = '1'; 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 种方式表达:
Single quotes
Double quotes
- ##heredoc syntax structure
- nowdoc Syntax structure
variables and escaping sequences of special characters will not be replaced in single-quoted strings.
Double quotesIf the string is surrounded by double quotes ("), PHP will parse some special characters:Sequence | Meaning |
---|---|
Line break (ASCII character set LF or 0x0A (10)) | |
Carriage Return (CR or 0x0D (13) in the ASCII character set) | |
Horizontal tab character (HT or 0x09 (9) in the ASCII character set) | |
Vertical tab character ( VT or 0x0B (11) in ASCII character set) (since PHP 5.2.5) | |
Escape (ESC or 0x1B (27) in ASCII character set) (Since PHP 5.4.0) | |
Page feed (FF or 0x0C (12) in ASCII character set) (Since PHP 5.2.5) | |
Backslash | |
Dollar mark | |
Double quotes | |
The one that matches this regular expression sequence is a The characters expressed in octal format | |
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!

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 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.

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 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.

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

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.

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 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool