Php 简明教程

PHP – Data Types

“数据类型”一词是指将数据分类到不同类别中。PHP 共有八种数据类型,我们使用这些数据类型构造变量−

The term "data types" refers to the classification of data in distinct categories. PHP has a total of eight data types that we use to construct our variables −

  1. Integers − Whole numbers, without a decimal point, like 4195.

  2. Doubles − Floating-point numbers like 3.14159 or 49.1.

  3. Booleans − Have only two possible values, either true or false.

  4. NULL − Special type that only has one value: NULL.

  5. Strings − Sequences of characters, like 'PHP supports string operations.'

  6. Arrays − Named and indexed collections of other values.

  7. Objects − Instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.

  8. Resources − Special variables that hold references to resources external to PHP (such as database connections).

前五个是简单类型,后两个(数组和对象)是复合类型。复合类型可以打包任意类型的其他任意值,而简单类型则不能。

The first five are simple types, and the next two (arrays and objects) are compound types. The compound types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.

在本章中,让我们详细讨论 PHP 的这些内置数据类型。

In this chapter, let’s discuss in detail about these built-in data types of PHP.

Integer Data Type in PHP

没有小数点(例如 4195)的整数在 PHP 中为 int 类型。整型数据类型是最简单的类型。它们对应于简单的整数,包括正数和负数。

A whole number without a decimal point (like 4195) is of int type in PHP. Integer data types are the simplest type. They correspond to simple whole numbers, both positive and negative.

  1. An int is a number of the set Z = {…​, -2, -1, 0, 1, 2, …​}.

  2. An int can be represented in a decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation.

要使用八进制记法,数字应加上前缀“0o”或“0O”。要使用十六进制记法,数字应加上前缀“0x”。要使用二进制记法,数字应加上前缀“0b”。

To use octal notation, a number is preceded with "0o" or "0O". To use hexadecimal notation, precede the number with "0x". To use binary notation, precede the number with "0b".

下面给出一些 examples -

Given below are some examples

  1. Decimal Integer − 201, 4195, -15

  2. Octal Integer − 0010, 0O12, -0O21

  3. Hexadecimal Integer − 0x10, -0x100

  4. Binary Integer − 0b10101, -0b100

可以将整数分配给变量,也可以在表达式中使用它们,如下所示 -

Integers can be assigned to variables, or they can be used in expressions, like so −

$int_var = 12345;
$another_int = -12345 + 12345;

Double Data Type in PHP

双变量表示浮点数(也称为“浮点数”、“双精度数”或“实数”),即带分数部分的数字。分数部分跟在整数部分后面,中间用小数符号 (.) 分隔。

Double variables represent floating point numbers (also known as "floats", "doubles", or "real numbers") that are the numbers with a fractional component. The fractional component follows after the integer component separated by the decimal symbol (.)

Note − 双精度变量可以为正、负或零。

Note − A double variable can be positive, negative, or zero.

$var1 = 1.55
$var2 =-123.0

Scientific Float Notation

PHP还允许使用科学计数法表示小数点后具有更多位数的浮点数。符号“E”或“e”用于分隔整数部分和小数部分。

PHP also allows the use of scientific notation to represent a floating point number with more digits after the decimal point. The symbol "E" or "e" is used to separate the integer and fractional part.

− 1.2e3, 2.33e-4, 7E-10, 1.0E5

默认情况下,双精度打印时使用所需的小数位数。查看以下 example

By default, doubles print with the minimum number of decimal places needed. Take a look at the following example

<?php
   $many = 2.2888800;
   $many_2 = 2.2111200;
   $few = $many + $many_2;

   print("$many + $many_2 = $few");
?>

它生成下列内容 output

It produces the following output

2.28888 + 2.21112 = 4.5

Boolean Data Type in PHP

bool 类型只有两个值;它可以为真或假。 bool 类型用于表示真值。

The bool type only has only two values; it can either be True or False. The bool type is used to express a truth value.

$bool1 = true;
$bool2 = false;

你也可以使用整数值“1”和“0”来表示真和假布尔值 −

You can also use the integer values "1" and "0" to represent True and False Boolean values −

$bool3 = 1;
$bool4 = 0;

通常,返回布尔值的运算符的结果将传递给诸如 if, whiledo-while 之类的控制结构。例如,

Typically, the result of an operator which returns a bool value is passed on to a control structure such as if, while or do-while. For example,

if (TRUE)
   print("This will always print.");

else
   print("This will never print.");

Interpreting Other Data Types as Booleans

这里有一组规则,你可以使用它来将其他数据类型解释为布尔值 −

Here is a set of rules that you can use to interpret other data types as Booleans −

  1. If the value is a number, then it is False only if the value is equal to zero, otherwise the value is True.

  2. If the value is a string, it is False if the string is empty (has zero characters) or is the string "0", and is True otherwise.

  3. The values of type NULL are always False.

  4. If the value is an array, it is False if it contains no other values; True otherwise. For an object, containing a value means having a member variable that has been assigned a value.

  5. Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).

Note − 不要将双精度用于布尔值。

Note − Don’t use double as Booleans.

当在布尔上下文中使用这些变量中的每一个时,这些变量中每一个都有其名称中嵌入的真值。

Each of the following variables has the truth value embedded in its name when it is used in a Boolean context.

$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";

String Data Type in PHP

字符串是一系列字符,例如’PHP支持字符串操作'。

A string is a sequence of characters, for example, 'PHP supports string operations.'

在PHP中,一个字符和一个字节相同。它意味着PHP仅支持256个字符集,因此不提供本机Unicode支持。

In PHP, a character is the same as a byte. It means PHP only supports a 256 character set, and hence does not offer native Unicode support.

PHP支持单引号和双引号字符串的构建。以下两种表示在PHP中均有效 −

PHP supports single-quoted as well as double-quoted string formation. Both the following representations are valid in PHP −

$string_1 = "This is a string in double quotes";
$string_2 = 'This is a somewhat longer, singly quoted string';

以下是字符串类型的其他一些示例 −

Here are some more examples of string type −

$string_39 = "This string has thirty-nine characters";
$string_0 = "";		// a string with zero characters

单引号字符串几乎按原样对待,而双引号字符串用其值替换变量,并特别解释某些字符序列。

Single-quoted strings are treated almost literally, whereas double-quoted strings replace variables with their values as well as specially interpreting certain character sequences.

<?php
   $variable = "name";
   $literally = 'My $variable will not print!';

   print($literally);
   print "\n";

   $literally = "My $variable will print!";
   print($literally);
?>

当您运行此代码时,它将生成以下 output

When you run this code, it will produce the following output

My $variable will not print!
My name will print

字符串长度没有限制。在可用内存范围内,您可以创建任意长的字符串。

There are no artificial limits on string length. Within the bounds of available memory, you ought to be able to make arbitrarily long strings.

由双引号分隔的字符串(如“this”)将在 PHP 中通过以下两种方式进行预处理:

Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP −

  1. Certain character sequences beginning with backslash (\) are replaced with special characters.

  2. Variable names (starting with $) are replaced with string representations of their values.

转义序列替换如下:

The escape-sequence replacements are −

  1. \n is replaced by the newline character

  2. \r is replaced by the carriage-return character

  3. \t is replaced by the tab character

  4. \$ is replaced by the dollar sign itself ($)

  5. \" is replaced by a single double-quote (")

  6. \\ is replaced by a single backslash (\)

PHP 也有字符串数据类型的 HeredocNowdoc 表示法。

PHP also has Heredoc and Nowdoc representations of string data type.

Heredoc Representation of String Data Type

您可以使用 heredoc 将多行分配给单个字符串变量:

You can assign multiple lines to a single string variable using heredoc −

<?php
   $channel =<<<_XML_

   <channel>
      <title>What's For Dinner</title>
      <link>http://menu.example.com/ </link>
      <description>Choose what to eat tonight.</description>
   </channel>
   _XML_;

   echo <<< END
      This uses the "here document" syntax to output multiple lines with
	  variable interpolation. Note that the here document terminator must
	  appear on a line with just a semicolon. no extra whitespace!
   END;

   print $channel;
?>

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

This uses the "here document" syntax to output
multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!

<channel>
   <title>What's For Dinner</title>
   <link>http://menu.example.com/ </link>
   <description>Choose what to eat tonight.</description>
</channel>

Nowdoc Representation of String Data Type

heredoc 标识符的所有规则也适用于 nowdoc 标识符。 nowdoc 的指定方式与 heredoc 相同,但 nowdoc 中不进行解析。您可以使用 nowdoc 构造来嵌入大块文本,而无需使用任何转义字符。

All the rules for heredoc identifiers also apply to nowdoc identifiers. A nowdoc is specified just like a heredoc, but there is no parsing inside a nowdoc. You can use the nowdoc construct for embedding large blocks of text without having to use any escape characters.

nowdoc 使用与 heredoc 相同的 <<< 序列进行标识,但标识符用单引号括起来,例如 <<<'EOT'。Nowdoc 用于单引号字符串,就像 heredoc 用于双引号字符串一样。

A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier is enclosed in single quotes, e.g. <<<'EOT'. Nowdocs apply to single-quoted strings just the way heredocs apply to double-quoted strings.

请看以下示例:

Take a look at the following example −

<?php
   echo <<<'IDENTIFIER'
   As the cat cleared its throat with a refined "Meow",
   the squirrel chirped excitedly about its latest
   discovery of a hidden stash of peanut treasure!
   IDENTIFIER;
?>

运行代码并检查其输出:

Run the code and check its output −

As the cat cleared its throat with a refined "Meow",
the squirrel chirped excitedly about its latest
discovery of a hidden stash of peanut treasure!

Null Data Type in PHP

在 PHP 中,null 表示一个特殊类型,它只有一个值:NULL。未定义和 unset() 变量将变为值“null”。

In PHP, null represents a special type that only has one value: NULL. Undefined and unset() variables will resolve to the value "null".

程序员通常在 PHP 中使用 Null 数据类型来初始化变量或指示某个值缺失。

Programmers normally use the Null data type in PHP to initialize variables or to indicate that a value is missing.

若要给变量赋值为 NULL,只需像这样赋值:

To give a variable the NULL value, simply assign it like this −

$my_var = NULL;

根据惯例,特殊常量 NULL 为大写,但实际上它就是 case insensitive; 你也可以直接输入 −

The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed −

$my_var = null;

已分配了 NULL 的变量具有以下属性 −

A variable that has been assigned NULL has the following properties −

  1. It evaluates to FALSE in a Boolean context.

  2. It returns FALSE when tested with IsSet() function.

Note − PHP 中变量的数据类型在运行时根据赋值给它们的 值来确定。

Note − The data types of variables in PHP are determined at runtime based on the values that are assigned to them.

Array Data Type in PHP

PHP 中的一个数组是一个有序映射,一个键与一个或多个值相关联。PHP 数组使用 array() 函数定义,或使用将数据放入方括号中的简短表示法进行定义。

An array in PHP is an ordered map, a key is associated with one or more values. A PHP array is defined using the array() function, or with the use of a short notation where the data is put in square brackets.

请看以下 associative arrays 示例 −

Take a look at the following examples of associative arrays

Using the array() Function

$arr = array(
   "foo" => "bar",
   "bar" => "foo",
);

Using the Short Notation

$arr = [
   "foo" => "bar",
   "bar" => "foo",
];

PHP 中的数组也可以使用“键 - 值对”语法定义。它被称为 indexed array

An array in PHP can also be defined with the "key-value pair" syntax. It is called an indexed array.

$arr = array("foo", "bar", "hello", "world");

multi-dimensional array 中,主数组中的每个元素也可以是一个数组。而且,子数组中的每个元素也可以是一个数组,依此类推。使用多重索引访问多维数组中的值。

In a multi-dimensional array, each element in the main array can also be an array. And, each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Note − 在 PHP 中,复合数据类型用于存储数据集合,包括数组和对象。

Note − In PHP, compound data types are used to store collections of data, including arrays and objects.

Object Data Type in PHP

对象类型是一个由程序员定义的类的实例,它可以将其他类型的值和特定于该类的函数打包在一起。

An object type is an instance of a programmer-defined class, which can package up both other kinds of values and functions that are specific to the class.

要创建一个新对象,请使用 new statement 实例化一个类 −

To create a new object, use the new statement to instantiate a class −

class foo {
   function bar() {
      echo "Hello World.";
   }
}
$obj = new foo;
$obj->bar();

Resource Data Type in PHP

资源是保存对 PHP 外部资源(如文件流或数据库连接)的引用的特殊变量。

Resources are special variables that hold references to resources external to PHP (such as a file stream or database connections).

以下是一个 file resource 示例 −

Here is an example of file resource

$fp = fopen("foo.txt", "w");

属于以上任何类型的的数据都存储在一个变量中。但是,由于 PHP 是一种动态类型语言,因此无需指定变量的类型,因为这将在运行时确定。

Data belonging to any of the above types is stored in a variable. However, since PHP is a dynamically typed language, there is no need to specify the type of a variable, as this will be determined at runtime.

Example: The gettype() Function

gettype() 函数有助于找出存储在变量中的数据类型 −

The gettype() function is helpful to find out the type of data stored in a variable −

<?php
   $x = 10;
   echo gettype($x) . "\n";

   $y = 10.55;
   echo gettype($y) . "\n";

   $z = [1,2,3,4,5];
   echo gettype($z);
?>

当您运行此代码时,它将生成以下 output

When you run this code, it will produce the following output

integer
double
array