Home > Article > Backend Development > Types - PHP Manual Notes
Type introduction
PHP supports 8 primitive data types.
Four scalar types:
Two compound types:
Finally there are two special types:
If you want to check the value and type of an expression, use the var_dump()
function.
<code><?php $a = array(1, 2, array("a", "b", "c")); var_dump($a); $b = 3.1; $c = true; var_dump($b, $c);</code>
The above code prints variable-related information through var_dump()
, and the output results are as follows (PHP version 5.5.12).
<code>array (size=3) 0 => int 1 1 => int 2 2 => array (size=3) 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) float 3.1 boolean true</code>
If you just want to get an easy-to-read type expression for debugging, use the gettype()
function. To check a certain type, don’t use gettype()
, but use the is_type
function. Use is_type
to filter parameters.
If you want to force a variable to a certain type, you can use cast or settype()
function. Note that variables can take on different values in certain situations depending on their type at the time.
boolean Boolean type
Special note that when converted to boolean, the following values are considered FALSE:
As long as it is an object, the return value is TRUE.
The following program can deepen your understanding of boolean type conversion.
<code><?php var_dump((bool) array()); // boolean false var_dump((bool) ""); // boolean false var_dump((bool) "0"); // boolean false var_dump((bool) "00"); // boolean true var_dump((bool) "false"); // boolean true var_dump((bool) (new stdClass())); // boolean true var_dump((bool) ((object) array())); // boolean true</code>
integer integer type
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 expression, 0b must be added before the number.
Binary expressed integer is available since PHP 5.4.0.
integer value can be represented by the constant PHP_INT_SIZE
, and the maximum value can be represented by the constant PHP_INT_MAX
.
<code><?php var_dump(PHP_INT_SIZE); // int 4 var_dump(PHP_INT_MAX); // int 2147483647 var_dump(01090); // int 8 八进制 010 = 十进制 8</code>
In the last statement of the above program, a strange thing happened when processing octal. That's because if you pass an illegal number (i.e. 8 or 9) to an octal number, the remaining digits will be ignored.
If a given number exceeds the range of integer, it will be interpreted as float. Similarly, if the result of the operation exceeds the range of integer, float will be returned.
There is no integer division operator in PHP. 1/2 yields float 0.5. The value can be cast to an integer, discarding the decimal part, or using the round()
function for better rounding.
The manual says to never cast an unknown fraction to an integer, as this can sometimes lead to unpredictable results.
<code><?php echo (int)((0.1 + 0.7) * 10);</code>
The output result of this program is 7, never trust floating point numbers!
float floating point type
Certain mathematical operations produce a result represented by the constant NAN
. This result represents a value that is undefined or unrepresentable in floating-point arithmetic. Any loose or strict comparison of this value with any other value will result in FALSE.
string string
A string is composed of a series of characters, where each character is equivalent to one byte. The implementation is an array of bytes plus an integer specifying the buffer length. This means that PHP can only support a character set of 256 and therefore does not support Unicode. How is Chinese displayed? Write down your questions first.
Strings have 4 grammatical expressions:
Single quotes
To express a single quote itself, you need to escape it with a backslash () in front of it.
To express a backslash itself, use two backslashes ().
Any other backslash will be treated as the backslash itself.
However, if there is only one backslash in the string wrapped in single quotes, the backslash will also be output. Why is this?
Double quotes
Escape characters can be parsed. The most important feature is that variables will be parsed.
Both single quotes and double quotes support multi-line input of strings.
heredoc structure
This structure has been rarely used in previous programming. Let’s learn more about it here.
The structure is roughly as follows:
operator<<<
provide an identifier after it, and then a newline.
Next is the string itself.
Finally, use the previously defined identifier as the end mark.
The identifier quoted at the end must be in the first column of the line, which means that the identifier cannot be indented, and the line must not contain other characters except maybe a semicolon (;).
Heredocs structures cannot be used to initialize class properties. As of PHP 5.3, this restriction only works when the heredoc contains variables.
The Heredoc structure is like a double-quoted string without double quotes, and the escaping rules are the same as double quotes.
nowdoc structure
The structure ofnowdoc is similar to heredoc, except that the identifier following the operator <<<
must be enclosed in single quotes.
就象heredoc结构类似于双引号字符串,nowdoc结构是类似于单引号字符串的。nowdoc中不进行解析操作。这种结构很适合用于嵌入PHP代码或其它大段文本而无需对其中的特殊字符进行转义。nowdoc结构可以用在任意的静态数据环境中,最典型的示例是用来初始化类的属性或常量。
变量解析
变量解析有两种语法规则,一种是简单规则,一种是复杂规则。简单规则最常用、最方便,这里详细学习一下复杂语法规则。复杂规则语法的显著标记是用花括号包围的表达式。
复杂语法不是因为其语法复杂而得名,而是因为它可以使用复杂的表达式。 由于{无法被转义,只有$紧挨着{时才会被识别。
存取和修改
可以以数组形式访问字符串,用超出字符串长度的下标写入将会拉长该字符串并以空格填充。非整数类型下标会被转换成整数。写入时只用到了赋值字符串的第一个字符。用空字符串赋值则赋给的值是NULL字符。PHP的字符串在内部是字节组成的数组。因此用花括号访问或修改字符串对多字节字符集很不安全。
字符串可以用 '.'(点)运算符连接起来,注意 '+'(加号)运算符没有这个功能。
一个布尔值boolean的TRUE被转换成string的"1"。boolean的FALSE被转换成""(空字符串)。字符串转换为数值,该字符串的开始部分决定了它的值。如果该字符串以合法的数值开始,则使用该数值。否则其值为 0(零)。
PHP的优势就体现在字符串处理的方便上,对于string的操作有很多有用的函数,可以运用各种函数,还有正则表达式。
PHP 并不特别指明字符串的编码,字符串会被按照该脚本文件相同的编码方式来编码。因此,操作文本的函数必须假定字符串是如何编码的。不幸的是,PHP关于此的函数有很多变种,关于PHP的字符串处理函数还需多加学习。
array数组
PHP中的数组实际上是一个有序映射,映射是一种把values关联到keys的类型。
可以用array()语言结构来新建一个数组。它接受任意数量用逗号分隔的“键(key)=>值(value)对”。自5.4起可以使用短数组定义语法,用[]替代array()。key可以是integer或者string,value可以是任意类型。
key会有如下的强制转换和规则:
<code><?php $a = array('20' => 'a', '02' => 'b'); var_dump($a);</code>
通过上面的规则可知,这段代码的输出结果如下:
<code>array (size=2) 20 => string 'a' (length=1) '02' => string 'b' (length=1)</code>
如果给出方括号但没有指定键名,则取当前最大整数索引值,新的键名将是该值加上1(但是最小为0)。要删除某键值对,对其调用unset()
函数,该函数允许删除数组中的某个键,但要注意数组将不会重建索引。
<code><?php $a = array('a', 'b' => 'b'); $a[] = 'c'; var_dump($a); unset($a[1]); var_dump($a);</code>
对于上面这段程序,输出为:
<code>array (size=3) 0 => string 'a' (length=1) 'b' => string 'b' (length=1) 1 => string 'c' (length=1) array (size=2) 0 => string 'a' (length=1) 'b' => string 'b' (length=1)</code>
应该始终在用字符串表示的数组索引上加上引号。例如用$foo['bar']
而不是$foo[bar]
。此代码中有一个未定义的常量(bar)而不是字符串('bar'-注意引号),而 PHP 可能会在以后定义此常量。
foreach控制结构是专门用于数组的。它提供了一个简单的方法来遍历数组。
下面的示例程序,通过读取目录填充数组,这里涉及到几个函数的使用。
<code><?php $handle = opendir('.'); while(false !== ($file = readdir($handle))) { $files[] = $file; } closedir($handle); var_dump($files);</code>
对于任意integer,float,string,boolean和resource类型,如果将一个值转换为数组,将得到一个仅有一个元素的数组,其下标为 0,该元素即为此标量的值。
object对象
要创建一个新的对象 object,使用 new 语句实例化一个类。
如果将一个对象转换成对象,它将不会有任何变化。如果其它任何类型的值被转换成对象,将会创建一个内置类 stdClass 的实例。如果该值为 NULL,则新的实例为空。数组转换成对象将使键名成为属性名并具有相对应的值。对于任何其它的值,名为 scalar 的成员变量将包含该值。
<code><?php class foo { function do_foo() { echo 'Doint foo.'; } } $bar = new foo; $bar->do_foo(); var_dump($bar); $obj = (object) 'hello'; var_dump($obj);</code>
上面的示例程序输出结果为:
<code>Doint foo.object(foo)[1] object(stdClass)[2] public 'scalar' => string 'hello' (length=5)</code>
resource资源类型
资源resource是一种特殊变量,保存了到外部资源的一个引用。资源使用的所有外部资源都会被垃圾回收系统释放,很少需要手工释放内存。但是,持久数据库连接比较特殊,它们不会被垃圾回收系统销毁。
NULL
NULL类型只有一个值,就是不区分大小写的常量NULL。
callback回调类型
第一次接触到这个概念,有点陌生。
自PHP 5.4起可用callable类型指定回调类型callback。
手册示例程序中使用了很多call_user_func
函数,先把这函数理一下。call_user_func
把第一个参数作为回调函数(callback),并且将其余的参数作为回调函数的参数。返回回调函数的返回值,如果错误则返回FALSE。
回调函数可以是简单函数、对象方法、静态类方法,回调函数的几种使用方法如下所示:
<code><?php function my_callback_function() { echo 'hello, world.'; } call_user_func('my_callback_function');</code>
<code><?php class MyClass { static function myCallbackMethod() { echo 'Hello, world.'; } } call_user_func(array('MyClass', 'myCallbackMethod'));</code>
<code><?php class MyClass { static function myCallbackMethod() { echo 'Hello, world.'; } } $obj = new MyClass; call_user_func(array($obj, 'myCallbackMethod'));</code>
<code><?php class MyClass { static function myCallbackMethod() { echo 'Hello, world.'; } } call_user_func('MyClass::myCallbackMethod');</code>
<code><?php class A { public static function who() { echo "A\n"; } } class B extends A { public static function who() { echo "B\n"; } } call_user_func(array('B', 'parent::who'));</code>
除了普通的用户自定义函数外,create_function()
可以用来创建一个匿名回调函数。
类型转换
PHP是弱类型语言,变量类型根据使用该变量的上下文所决定的。
(全文完)
以上就介绍了类型 - PHP手册笔记,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。