Home >Backend Development >PHP Tutorial >Summary of new functions and features of each version of PHP5, new functions and features of php5_PHP tutorial
Because of PHP’s painful syntax that “gathers the strengths of hundreds of schools of thought”, coupled with the community atmosphere Unfortunately, many people are not interested in new versions and new features. This article will introduce the new features added in PHP5.2 starting from PHP5.6
Directory of this article:
PHP5.2 before: autoload, PDO and MySQLi, type constraints
PHP5.2: JSON support
PHP5.3: deprecated features, anonymous Functions, new magic methods, namespaces, late static binding, Heredoc and Nowdoc, const, ternary operator, Phar
PHP5.4: Short Open Tag, array abbreviation, Traits, built-in web server, details modified
PHP5.5: yield, list() is used for foreach, details modified
PHP5.6: constant enhancement, variable function parameters, namespace enhancement
1. Before PHP5.2 (before 2006)
By the way, let me introduce the features of PHP5.2 that have already appeared but are worth introducing.
autoload
Everyone may know the __autoload() function. If this function is defined, then when an undefined class is used in the code, the function will be called. You can load the corresponding class implementation file in this function, such as:
<span>function</span> __autoload(<span>$classname</span><span>) { </span><span>require_once</span>("{<span>$classname</span>}.php"<span>) }</span><span>/*</span><span> 何问起 hovertree.com </span><span>*/</span>
But this function is no longer recommended because there can only be one such __autoload() function in a project because PHP does not allow functions with duplicate names. But when you use some class libraries, you will inevitably need multiple autoload functions, so spl_autoload_register() replaces it:
spl_autoload_register(<span>function</span>(<span>$classname</span><span>) { </span><span>require_once</span>("{<span>$classname</span>}.php"<span>) });</span><span>/*</span><span> hovertree.top </span><span>*/</span>
spl_autoload_register() will register a function into the autoload function list. When an undefined class appears, SPL [Note] will call the registered autoload functions one by one in the reverse order of registration, which means you can use spl_autoload_register () Register multiple autoload functions.
Note: SPL: Standard PHP Library, standard PHP library, is designed to solve some classic problems (such as data structure).
PDO and MySQLi
are PHP Data Object, PHP data object, which is PHP’s new database access interface.
According to the traditional style, accessing the MySQL database should look like this:
<span>//</span><span> 连接到服务器,选择数据库</span> <span>$conn</span> = <span>mysql_connect</span>("localhost", "user", "password"<span>); </span><span>mysql_select_db</span>("database"<span>); </span><span>//</span><span> 执行 SQL 查询</span> <span>$type</span> = <span>$_POST</span>['type'<span>]; </span><span>$sql</span> = "SELECT * FROM `table` WHERE `type` = {<span>$type</span>}"<span>; </span><span>$result</span> = <span>mysql_query</span>(<span>$sql</span><span>); </span><span>//</span><span> 打印结果</span> <span>while</span>(<span>$row</span> = <span>mysql_fetch_array</span>(<span>$result</span>,<span> MYSQL_ASSOC)) { </span><span>foreach</span>(<span>$row</span> <span>as</span> <span>$k</span> => <span>$v</span><span>) </span><span>print</span> "{<span>$k</span>}: {<span>$v</span>}\n"<span>; } </span><span>//</span><span> 释放结果集,关闭连接</span> <span>mysql_free_result</span>(<span>$result</span><span>); </span><span>mysql_close</span>(<span>$conn</span><span>); </span><span>/*</span><span> hwq2.com </span><span>*/</span>
In order to make the code database independent, that is, a piece of code is applicable to multiple databases at the same time (for example, the above code is only applicable to MySQL), PHP officially designed PDO.
In addition, PDO also provides more Function, such as:
1. Object-oriented style interface
2. SQL pre-compilation (prepare), placeholder syntax
3. Higher execution efficiency, as an official recommendation, there are special performance optimizations
4 .Supports most SQL databases, no need to change the code when changing the database
The above code implemented with PDO will look like this:
<span>//</span><span> 连接到数据库</span> <span>$conn</span> = <span>new</span> PDO("mysql:host=localhost;dbname=database", "user", "password"<span>); </span><span>//</span><span> 预编译SQL, 绑定参数</span> <span>$query</span> = <span>$conn</span>->prepare("SELECT * FROM `table` WHERE `type` = :type"<span>); </span><span>$query</span>->bindParam("type", <span>$_POST</span>['type'<span>]); </span><span>//</span><span> 执行查询并打印结果</span> <span>foreach</span>(<span>$query</span>->execute() <span>as</span> <span>$row</span><span>) { </span><span>foreach</span>(<span>$row</span> <span>as</span> <span>$k</span> => <span>$v</span><span>) </span><span>print</span> "{<span>$k</span>}: {<span>$v</span>}\n"<span>; }</span><span>//</span><span> 何问起 hovertree.com</span>
PDO is officially recommended and a more general database access method. If you have no special needs, then you'd better learn and use PDO.
But if you need to use the advanced functions unique to MySQL, then you may You need to try MySQLi, because in order to be able to be used on multiple databases at the same time, PDO does not include those unique features of MySQL.
MySQLi is an enhanced interface for MySQL, providing both process-oriented and object-oriented interfaces. It is also the currently recommended MySQL driver. The old C-style MySQL interface will be closed by default in the future.
Compared with the above two pieces of code, the usage of MySQLi does not have many new concepts. Examples will not be given here. You can refer to the PHP official website documentation [Note].
Note: http://www.php.net/manual/en/mysqli.quickstart.php
Type Constraints
Type constraints can limit the type of parameters, but this mechanism is not perfect and currently only applies to classes, callables (executable types) and arrays (arrays), not Applies to string and int.
<span>//</span><span> 限制第一个参数为 MyClass, 第二个参数为可执行类型,第三个参数为数组</span> <span>function</span> MyFunction(MyClass <span>$a</span>, callable <span>$b</span>, <span>array</span> <span>$c</span><span>) { </span><span>//</span><span> ...</span> }<span>//</span><span> 何问起 hovertree.com</span>
PHP5.2(2006-2011): JSON support
Including json_encode(), json_decode() and other functions. JSON is a very commonly used data exchange format in the Web field and can be directly supported by JS. JSON is actually part of the JS syntax.
JSON series functions can convert array structures in PHP into JSON strings:
<span>$array</span> = ["key" => "value", "array" => [1, 2, 3, 4<span>]]; </span><span>$json</span> = json_encode(<span>$array</span><span>); </span><span>echo</span> "{<span>$json</span>}\n"<span>; </span><span>$object</span> = json_decode(<span>$json</span><span>); </span><span>print_r</span>(<span>$object</span>);<span>/*</span><span> hovertree.top </span><span>*/</span>
Output:
<span>{"key":"value","array":[1,2,3,4]} stdClass Object ( [key] => value [array] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) )</span>
It is worth noting that json_decode() will return an object instead of an array by default. If you need to return an array, you need to set the second parameter to true.
PHP5.3 (2009-2012)
PHP5.3 is a very big update, adding a lot of new features, and also made some modifications that are not backward compatible.
【PHP5.3 deprecated features】: The following features are deprecated. If enabled in the configuration file, PHP will issue a warning at runtime.
Register Globals
This is an option in php.ini (register_globals). When turned on, all form variables ($_GET and $_POST) will be registered as global variables.
See Example below:
<span>if</span><span>(isAuth()) </span><span>$authorized</span> = <span>true</span><span>; </span><span>if</span>(<span>$authorized</span><span>) </span><span>include</span>("page.php");<span>/*</span><span> hovertree.top </span><span>*/</span>
这段代码在通过验证时,将 $authorized 设置为 true. 然后根据 $authorized 的值来决定是否显示页面.
但由于并没有事先把 $authorized 初始化为 false, 当 register_globals 打开时,可能访问 /auth.php?authorized=1 来定义该变量值,绕过身份验证。
该特征属于历史遗留问题,在 PHP4.2 中被默认关闭,在 PHP5.4 中被移除。
Magic Quotes
对应 php.ini 中的选项 magic_quotes_gpc, 这个特征同样属于历史遗留问题,已经在 PHP5.4 中移除。
该特征会将所有用户输入进行转义,这看上去不错,在第一章我们提到过要对用户输入进行转义。
但是 PHP 并不知道哪些输入会进入 SQL , 哪些输入会进入 Shell, 哪些输入会被显示为 HTML, 所以很多时候这种转义会引起混乱。
Safe Mode
很多虚拟主机提供商使用 Safe Mode 来隔离多个用户,但 Safe Mode 存在诸多问题,例如某些扩展并不按照 Safe Mode 来进行权限控制。
PHP官方推荐使用操作系统的机制来进行权限隔离,让Web服务器以不同的用户权限来运行PHP解释器,请参见第一章中的最小权限原则.
【PHP5.3的新增、改进】
匿名函数
也叫闭包(Closures), 经常被用来临时性地创建一个无名函数,用于回调函数等用途。
<span>$func</span> = <span>function</span>(<span>$arg</span><span>) { </span><span>print</span> <span>$arg</span><span>; }; </span><span>$func</span>("Hello World! hovertree.top");
以上代码定义了一个匿名函数,并赋值给了 $func.
可以看到定义匿名函数依旧使用 function 关键字,只不过省略了函数名,直接是参数列表。
然后我们又调用了 $func 所储存的匿名函数。
匿名函数还可以用 use 关键字来捕捉外部变量:
<span>function</span> arrayPlus(<span>$array</span>, <span>$num</span><span>) { </span><span>array_walk</span>(<span>$array</span>, <span>function</span>(&<span>$v</span>) <span>use</span>(<span>$num</span><span>){ </span><span>$v</span> += <span>$num</span><span>; }); }</span><span>/*</span><span> hovertree.top </span><span>*/</span>
上面的代码定义了一个 arrayPlus() 函数(这不是匿名函数), 它会将一个数组($array)中的每一项,加上一个指定的数字($num).
在 arrayPlus() 的实现中,我们使用了 array_walk() 函数,它会为一个数组的每一项执行一个回调函数,即我们定义的匿名函数。
在匿名函数的参数列表后,我们用 use 关键字将匿名函数外的 $num 捕捉到了函数内,以便知道到底应该加上多少。
魔术方法:__invoke(), __callStatic()
PHP 的面向对象体系中,提供了若干“魔术方法”,用于实现类似其他语言中的“重载”,如在访问不存在的属性、方法时触发某个魔术方法。
随着匿名函数的加入,PHP 引入了一个新的魔术方法 __invoke().
该魔术方法会在将一个对象作为函数调用时被调用:
<span>class</span><span> A { </span><span>public</span> <span>function</span> __invoke(<span>$str</span><span>) { </span><span>print</span> "A::__invoke(): {<span>$str</span>}"<span>; } } </span><span>$a</span> = <span>new</span><span> A; </span><span>$a</span>("Hello World!何问起");
输出毫无疑问是:
A::__invoke(): Hello World
__callStatic() 则会在调用一个不存在的静态方法时被调用。
命名空间
PHP的命名空间有着前无古人后无来者的无比蛋疼的语法:
<?<span>php </span><span>//</span><span> 命名空间的分隔符是反斜杠,该声明语句必须在文件第一行。 // 命名空间中可以包含任意代码,但只有 **类, 函数, 常量** 受命名空间影响。</span> <span>namespace XXOO\Test; </span><span>//</span><span> 该类的完整限定名是 \XXOO\Test\A , 其中第一个反斜杠表示全局命名空间。</span> <span>class</span><span> A{} </span><span>//</span><span> 你还可以在已经文件中定义第二个命名空间,接下来的代码将都位于 \Other\Test2 .</span> <span>namespace Other\Test2; </span><span>//</span><span> 实例化来自其他命名空间的对象:</span> <span>$a</span> = <span>new</span><span> \XXOO\Test\A; </span><span>class</span><span> B{} </span><span>//</span><span> 你还可以用花括号定义第三个命名空间</span><span> /*</span><span> 何问起 hovertree.com </span><span>*/</span><span> namespace Other { </span><span>//</span><span> 实例化来自子命名空间的对象:</span> <span>$b</span> = <span>new</span><span> Test2\B; </span><span>//</span><span> 导入来自其他命名空间的名称,并重命名, // 注意只能导入类,不能用于函数和常量。</span> <span>use</span> \XXOO\Test\A <span>as</span><span> ClassA } </span>?>
更多有关命名空间的语法介绍请参见官网 [注].
命名空间时常和 autoload 一同使用,用于自动加载类实现文件:
<span>spl_autoload_register( </span><span>function</span> (<span>$class</span><span>) { spl_autoload(</span><span>str_replace</span>("\\", "/", <span>$class</span><span>)); } );</span>
当你实例化一个类 \XXOO\Test\A 的时候,这个类的完整限定名会被传递给 autoload 函数,autoload 函数将类名中的命名空间分隔符(反斜杠)替换为斜杠,并包含对应文件。
这样可以实现类定义文件分级储存,按需自动加载。
注:http://www.php.net/manual/zh/language.namespaces.php
后期静态绑定
PHP 的 OPP 机制,具有继承和类似虚函数的功能,例如如下的代码:
<span>class</span><span> A { </span><span>public</span> <span>function</span><span> callFuncXXOO() { </span><span>print</span> <span>$this</span>-><span>funcXXOO(); } </span><span>public</span> <span>function</span><span> funcXXOO() { </span><span>return</span> "A::funcXXOO()"<span>; } } </span><span>class</span> B <span>extends</span><span> A { </span><span>public</span> <span>function</span><span> funcXXOO() { </span><span>return</span> "B::funcXXOO"<span>; } } </span><span>$b</span> = <span>new</span><span> B; </span><span>$b</span>->callFuncXXOO();<span>/*</span><span> 何问起 hovertree.com </span><span>*/</span>
输出是:
B::funcXXOO
可以看到,当在 A 中使用 $this->funcXXOO() 时,体现了“虚函数”的机制,实际调用的是 B::funcXXOO().
然而如果将所有函数都改为静态函数:
<span>class</span><span> A { </span><span>static</span> <span>public</span> <span>function</span><span> callFuncXXOO() { </span><span>print</span> self::<span>funcXXOO(); } </span><span>static</span> <span>public</span> <span>function</span><span> funcXXOO() { </span><span>return</span> "A::funcXXOO()"<span>; } } </span><span>class</span> B <span>extends</span><span> A { </span><span>static</span> <span>public</span> <span>function</span><span> funcXXOO() { </span><span>return</span> "B::funcXXOO"<span>; } } </span><span>$b</span> = <span>new</span><span> B; </span><span>$b</span>->callFuncXXOO();
情况就没这么乐观了,输出是:
A::funcXXOO()
这是因为 self 的语义本来就是“当前类”,所以 PHP5.3 给 static 关键字赋予了一个新功能:后期静态绑定:
<span>class</span><span> A { </span><span>static</span> <span>public</span> <span>function</span><span> callFuncXXOO() { </span><span>print</span> <span>static</span>::<span>funcXXOO(); } </span><span>//</span><span> ...</span> <span>} </span><span>//</span><span> ...</span>
这样就会像预期一样输出了:
B::funcXXOO
Heredoc 和 Nowdoc
PHP5.3 对 Heredoc 以及 Nowdoc 进行了一些改进,它们都用于在 PHP 代码中嵌入大段字符串。
Heredoc 的行为类似于一个双引号字符串:
<span>$name</span> = "MyName"<span>; </span><span>echo</span> <<<<span> TEXT My name is </span>"{<span>$name</span>}".<span> TEXT;</span>
Heredoc 以三个左尖括号开始,后面跟一个标识符(TEXT), 直到一个同样的顶格的标识符(不能缩进)结束。
就像双引号字符串一样,其中可以嵌入变量。
Heredoc 还可以用于函数参数,以及类成员初始化:
<span>var_dump</span>(<<<<span>EOD Hello World EOD ); </span><span>class</span><span> A { </span><span>const</span> xx = <<<<span> EOD Hello World EOD; </span><span>public</span> <span>$oo</span> = <<<<span> EOD Hello World EOD; }</span>
Nowdoc 的行为像一个单引号字符串,不能在其中嵌入变量,和 Heredoc 唯一的区别就是,三个左尖括号后的标识符要以单引号括起来:
<span>$name</span> = "MyName"<span>; </span><span>echo</span> <<< 'TEXT'<span> My name is </span>"{<span>$name</span>}".<span> TEXT;</span>
输出:
My name is "{<span>$name</span>}".
用 const 定义常量
PHP5.3 起同时支持在全局命名空间和类中使用 const 定义常量。
旧式风格:
<span>define</span>("XOOO", "Value");
新式风格:
const XXOO = "Value";
const 形式仅适用于常量,不适用于运行时才能求值的表达式:
<span>//</span><span> 正确</span> <span>const</span> XXOO = 1234<span>; </span><span>//</span><span> 错误</span> <span>const</span> XXOO = 2 * 617;
三元运算符简写形式
旧式风格:
<span>echo</span> <span>$a</span> ? <span>$a</span> : "No Value";
可简写成:
<span>echo</span> <span>$a</span> ?: "No Value";
即如果省略三元运算符的第二个部分,会默认用第一个部分代替。
Phar
Phar即PHP Archive, 起初只是Pear中的一个库而已,后来在PHP5.3被重新编写成C扩展并内置到 PHP 中。
Phar用来将多个 .php 脚本打包(也可以打包其他文件)成一个 .phar 的压缩文件(通常是ZIP格式)。
目的在于模仿 Java 的 .jar, 不对,目的是为了让发布PHP应用程序更加方便。同时还提供了数字签名验证等功能。
.phar 文件可以像 .php 文件一样,被PHP引擎解释执行,同时你还可以写出这样的代码来包含(require) .phar 中的代码:
<span>require</span>("xxoo.phar"<span>); </span><span>require</span>("phar://xxoo.phar/xo/ox.php");
更多信息请参见官网 [注].
注:http://www.php.net/manual/zh/phar.using.intro.php
PHP5.4(2012-2013)
Short Open Tag
Short Open Tag 自 PHP5.4 起总是可用。
在这里集中讲一下有关 PHP 起止标签的问题。即:
<?<span>php </span><span>//</span><span> Code... 何问起 hovertree.com</span> ?>
通常就是上面的形式,除此之外还有一种简写形式:
<? <span>/*</span><span> Code... </span><span>*/</span> ?>
还可以把
<?php <span>echo</span> <span>$xxoo</span>;?>
简写成:
<?= <span>$xxoo</span>;?>
这种简写形式被称为 Short Open Tag, 在 PHP5.3 起被默认开启,在 PHP5.4 起总是可用。
使用这种简写形式在 HTML 中嵌入 PHP 变量将会非常方便。
对于纯 PHP 文件(如类实现文件), PHP 官方建议顶格写起始标记,同时 省略 结束标记。
这样可以确保整个 PHP 文件都是 PHP 代码,没有任何输出,否则当你包含该文件后,设置 Header 和 Cookie 时会遇到一些麻烦 [注].
注:Header 和 Cookie 必须在输出任何内容之前被发送。
数组简写形式
这是非常方便的一项特征!
<span>//</span><span> 原来的数组写法</span> <span>$arr</span> = <span>array</span>("key" => "value", "key2" => "value2"<span>); </span><span>//</span><span> 简写形式</span> <span>$arr</span> = ["key" => "value", "key2" => "value2"<span>]; </span><span>//</span><span> 何问起 hovertree.com</span>
Traits
所谓Traits就是“构件”,是用来替代继承的一种机制。PHP中无法进行多重继承,但一个类可以包含多个Traits.
<span>//</span><span> Traits不能被单独实例化,只能被类所包含</span> <span>trait SayWorld { </span><span>public</span> <span>function</span><span> sayHello() { </span><span>echo</span> 'World!'<span>; } } </span><span>class</span><span> MyHelloWorld { </span><span>//</span><span> 将SayWorld中的成员包含进来</span> <span>use</span><span> SayWorld; } </span><span>$xxoo</span> = <span>new</span><span> MyHelloWorld(); </span><span>//</span><span> sayHello() 函数是来自 SayWorld 构件的</span> <span>$xxoo</span>->sayHello();
Traits还有很多神奇的功能,比如包含多个Traits, 解决冲突,修改访问权限,为函数设置别名等等。
Traits中也同样可以包含Traits. 篇幅有限不能逐个举例,详情参见官网 [注].
注:http://www.php.net/manual/zh/language.oop5.traits.php
内置 Web 服务器
PHP从5.4开始内置一个轻量级的Web服务器,不支持并发,定位是用于开发和调试环境。
在开发环境使用它的确非常方便。
php -S localhost:8000
这样就在当前目录建立起了一个Web服务器,你可以通过 http://localhost:8000/ 来访问。
其中localhost是监听的ip,8000是监听的端口,可以自行修改。
很多应用中,都会进行URL重写,所以PHP提供了一个设置路由脚本的功能:
php -S localhost:8000 index.php
这样一来,所有的请求都会由index.php来处理。
你还可以使用 XDebug 来进行断点调试。
细节修改
PHP5.4 新增了动态访问静态方法的方式:
<span>$func</span> = "funcXXOO"<span>; A</span>::{<span>$func</span>}();
新增在实例化时访问类成员的特征:
(<span>new</span> MyClass)->xxoo();
新增支持对函数返回数组的成员访问解析(这种写法在之前版本是会报错的):
<span>print</span> func()[0];
PHP5.5(2013起)
yield
yield关键字用于当函数需要返回一个迭代器的时候, 逐个返回值。
<span>function</span><span> number10() { </span><span>for</span>(<span>$i</span> = 1; <span>$i</span> <= 10; <span>$i</span> += 1<span>) yield </span><span>$i</span><span>; }</span>
该函数的返回值是一个数组:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list() 用于 foreach
可以用 list() 在 foreach 中解析嵌套的数组:
<span>$array</span> =<span> [ [</span>1, 2, 3],<span> [</span>4, 5, 6],<span> ]; </span><span>foreach</span> (<span>$array</span> <span>as</span> <span>list</span>(<span>$a</span>, <span>$b</span>, <span>$c</span><span>)) </span><span>echo</span> "{<span>$a</span>} {<span>$b</span>} {<span>$c</span>}\n";
结果:
1 2 3 4 5 6
细节修改
不推荐使用 mysql 函数,推荐使用 PDO 或 MySQLi, 参见前文。
不再支持Windows XP.
可用 MyClass::class 取到一个类的完整限定名(包括命名空间)。
empty() 支持表达式作为参数。
try-catch 结构新增 finally 块。
PHP5.6
更好的常量
定义常量时允许使用之前定义的常量进行计算:
<span>const</span> A = 2<span>; </span><span>const</span> B = A + 1<span>; </span><span>class</span><span> C { </span><span>const</span> STR = "hello"<span>; </span><span>const</span> STR2 = self::STR + ", world"<span>; }</span>
允许常量作为函数参数默认值:
<span>function</span> func(<span>$arg</span> = C::STR2)
更好的可变函数参数
用于代替 func_get_args()
<span>function</span> add(...<span>$args</span><span>) { </span><span>$result</span> = 0<span>; </span><span>foreach</span>(<span>$args</span> <span>as</span> <span>$arg</span><span>) </span><span>$result</span> += <span>$arg</span><span>; </span><span>return</span> <span>$result</span><span>; }</span><span>//</span><span> 何问起 hovertree.com</span>
同时可以在调用函数时,把数组展开为函数参数:// 结果为 6
命名空间
命名空间支持常量和函数:
<span>namespace Name\Space { </span><span>const</span> FOO = 42<span>; </span><span>function</span> f() { <span>echo</span> <span>__FUNCTION__</span>."\n"<span>; } } namespace { </span><span>use</span> <span>const</span><span> Name\Space\FOO; </span><span>use</span> <span>function</span><span> Name\Space\f; </span><span>echo</span> FOO."\n"<span>; f(); }</span>
推荐:http://www.cnblogs.com/roucheng/p/3454913.html