Summary of new functions and features of each version of PHP5

PHPz
Release: 2022-07-27 11:57:45
forward
1201 people have browsed it

Because of PHP’s painful syntax that “gathers the strengths of hundreds of schools of thought” and the poor community atmosphere, many people are not interested in new versions and new features. This article will introduce the new features added in PHP5.2 up to PHP5.6

Directory of this article:

Before PHP5.2: 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, PHP5.2 has already appeared but is worth introducing characteristics.

autoload

Everyone may know the __autoload() function. If this function is defined, then when an undefined class is used in the code, the The function will be called, and you can load the corresponding class implementation file in this function, such as:

function __autoload($classname)
{    require_once("{$classname}.php")
}/* 何问起 hovertree.com */
Copy after login

But this function is no longer recommended for use because it is used in a project There can be only one such __autoload() function 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(function($classname)
{    require_once("{$classname}.php")
});/* hovertree.top */
Copy after login

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() to register multiple autoload functions.
Note: SPL: Standard PHP Library , a standard PHP library, designed to solve some classic problems (such as data structures).

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:

// 连接到服务器,选择数据库
$conn = mysql_connect("localhost", "user", "password");
mysql_select_db("database");
// 执行 SQL 查询
$type = $_POST['type'];
$sql = "SELECT * FROM `table` WHERE `type` = {$type}";
$result = mysql_query($sql);
// 打印结果
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    foreach($row as $k => $v)
        print "{$k}: {$v}
";
}
// 释放结果集,关闭连接
mysql_free_result($result);
mysql_close($conn);
/* hwq2.com */
Copy after login

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 only applies to MySQL), PHP officially designed PDO.
In addition, PDO also provides more functions, such as:

1. Object-oriented style interface
2. SQL precompilation (prepare), placeholder syntax
3. Higher execution efficiency, as an official recommendation, with special performance optimization
4. Supports most SQL databases, no need to change the code when changing the database

The above code implemented using PDO will look like this:

// 连接到数据库
$conn = new PDO("mysql:host=localhost;dbname=database", "user", "password");
// 预编译SQL, 绑定参数
$query = $conn->prepare("SELECT * FROM `table` WHERE `type` = :type");
$query->bindParam("type", $_POST['type']);
// 执行查询并打印结果
foreach($query->execute() as $row)
{
    foreach($row as $k => $v)
        print "{$k}: {$v}
";
}// 何问起 hovertree.com
Copy after login

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 advanced features unique to MySQL, then you may want to try MySQLi, because PDO will not include those unique to MySQL in order to be used on multiple databases at the same time. function.

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

By type constraints You can limit the type of parameters, but this mechanism is not perfect. Currently it only applies to classes, callables (executable types) and arrays, but not to strings and ints.

// 限制第一个参数为 MyClass, 第二个参数为可执行类型,第三个参数为数组
function MyFunction(MyClass $a, callable $b, array $c)
{
    // ...
}// 何问起 hovertree.com
Copy after login

PHP5.2 (2006-2011): JSON supports

including json_encode(), json_decode() and other functions. JSON is a very commonly used data exchange format in the Web field. 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:

$array = ["key" => "value", "array" => [1, 2, 3, 4]];
$json = json_encode($array);
echo "{$json}
";
$object = json_decode($json);
print_r($object);/* hovertree.top */
Copy after login

Output:

{"key":"value","array":[1,2,3,4]}
stdClass Object
(
    [key] => value
    [array] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )
)
Copy after login

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 making 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.
Look at the example below:

if(isAuth())
    $authorized = true;
if($authorized)
    include("page.php");/* hovertree.top */
Copy after login

这段代码在通过验证时,将 $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), 经常被用来临时性地创建一个无名函数,用于回调函数等用途。

$func = function($arg)
{
    print $arg;
};
$func("Hello World! hovertree.top");
Copy after login

以上代码定义了一个匿名函数,并赋值给了 $func.
可以看到定义匿名函数依旧使用 function 关键字,只不过省略了函数名,直接是参数列表。
然后我们又调用了 $func 所储存的匿名函数。
匿名函数还可以用 use 关键字来捕捉外部变量:

function arrayPlus($array, $num)
{    array_walk($array, function(&$v) use($num){        $v += $num;
    });
}/* hovertree.top */
Copy after login

上面的代码定义了一个 arrayPlus() 函数(这不是匿名函数), 它会将一个数组($array)中的每一项,加上一个指定的数字($num).
在 arrayPlus() 的实现中,我们使用了 array_walk() 函数,它会为一个数组的每一项执行一个回调函数,即我们定义的匿名函数。
在匿名函数的参数列表后,我们用 use 关键字将匿名函数外的 $num 捕捉到了函数内,以便知道到底应该加上多少。

魔术方法:__invoke(), __callStatic()
PHP 的面向对象体系中,提供了若干“魔术方法”,用于实现类似其他语言中的“重载”,如在访问不存在的属性、方法时触发某个魔术方法。
随着匿名函数的加入,PHP 引入了一个新的魔术方法 __invoke().
该魔术方法会在将一个对象作为函数调用时被调用:

class A
{    public function __invoke($str)
    {        print "A::__invoke(): {$str}";
    }
}$a = new A;$a("Hello World!何问起");
Copy after login

输出毫无疑问是:

A::__invoke(): Hello World
Copy after login

__callStatic() 则会在调用一个不存在的静态方法时被调用。


命名空间
PHP的命名空间有着前无古人后无来者的无比蛋疼的语法:

<?php
// 命名空间的分隔符是反斜杠,该声明语句必须在文件第一行。
// 命名空间中可以包含任意代码,但只有 **类, 函数, 常量** 受命名空间影响。
namespace XXOOTest;
// 该类的完整限定名是 XXOOTestA , 其中第一个反斜杠表示全局命名空间。
class A{}
// 你还可以在已经文件中定义第二个命名空间,接下来的代码将都位于 OtherTest2 .
namespace OtherTest2;
// 实例化来自其他命名空间的对象:
$a = new XXOOTestA;
class B{}
// 你还可以用花括号定义第三个命名空间
/* 何问起 hovertree.com */
namespace Other {
    // 实例化来自子命名空间的对象:
    $b = new Test2B;
    // 导入来自其他命名空间的名称,并重命名,
    // 注意只能导入类,不能用于函数和常量。
    use XXOOTestA as ClassA
}
?>
Copy after login

更多有关命名空间的语法介绍请参见官网 [注].
命名空间时常和 autoload 一同使用,用于自动加载类实现文件:

spl_autoload_register(    function ($class) {
        spl_autoload(str_replace("\", "/", $class));
    }
);
Copy after login

当你实例化一个类 XXOOTestA 的时候,这个类的完整限定名会被传递给 autoload 函数,autoload 函数将类名中的命名空间分隔符(反斜杠)替换为斜杠,并包含对应文件。
这样可以实现类定义文件分级储存,按需自动加载。
注:http://www.php.net/manual/zh/language.namespaces.php

后期静态绑定
PHP 的 OPP 机制,具有继承和类似虚函数的功能,例如如下的代码:

class A
{
    public function callFuncXXOO()
    {
        print $this->funcXXOO();
    }
    public function funcXXOO()
    {
        return "A::funcXXOO()";
    }
}
class B extends A
{
    public function funcXXOO()
    {
        return "B::funcXXOO";
    }
}
$b = new B;
$b->callFuncXXOO();/* 何问起 hovertree.com */
Copy after login

输出是:

B::funcXXOO
Copy after login
Copy after login

可以看到,当在 A 中使用 $this->funcXXOO() 时,体现了“虚函数”的机制,实际调用的是 B::funcXXOO().
然而如果将所有函数都改为静态函数:

class A
{
    static public function callFuncXXOO()
    {
        print self::funcXXOO();
    }
    static public function funcXXOO()
    {
        return "A::funcXXOO()";
    }
}
class B extends A
{
    static public function funcXXOO()
    {
        return "B::funcXXOO";
    }
}
$b = new B;
$b->callFuncXXOO();
Copy after login

情况就没这么乐观了,输出是:

A::funcXXOO()
Copy after login

这是因为 self 的语义本来就是“当前类”,所以 PHP5.3 给 static 关键字赋予了一个新功能:后期静态绑定:

class A
{
    static public function callFuncXXOO()
    {
        print static::funcXXOO();
    }
    // ...
}
// ...
Copy after login

这样就会像预期一样输出了:

B::funcXXOO
Copy after login
Copy after login

Heredoc 和 Nowdoc

PHP5.3 对 Heredoc 以及 Nowdoc 进行了一些改进,它们都用于在 PHP 代码中嵌入大段字符串。
Heredoc 的行为类似于一个双引号字符串:

$name = "MyName";echo <<< TEXT
My name is "{$name}".TEXT;
Copy after login

Heredoc 以三个左尖括号开始,后面跟一个标识符(TEXT), 直到一个同样的顶格的标识符(不能缩进)结束。
就像双引号字符串一样,其中可以嵌入变量。

Heredoc 还可以用于函数参数,以及类成员初始化:

var_dump(<<<EOD
Hello World
EOD
);
class A
{
    const xx = <<< EOD
Hello World
EOD;
    public $oo = <<< EOD
Hello World
EOD;
}
Copy after login

Nowdoc 的行为像一个单引号字符串,不能在其中嵌入变量,和 Heredoc 唯一的区别就是,三个左尖括号后的标识符要以单引号括起来:

$name = "MyName";
echo <<< &#39;TEXT&#39;
My name is "{$name}".
TEXT;
Copy after login

输出:

My name is "{$name}".
Copy after login

用 const 定义常量

PHP5.3 起同时支持在全局命名空间和类中使用 const 定义常量。
旧式风格:

define("XOOO", "Value");
Copy after login

新式风格:
const XXOO = "Value";
const 形式仅适用于常量,不适用于运行时才能求值的表达式:

// 正确
const XXOO = 1234;
// 错误
const XXOO = 2 * 617;
Copy after login

三元运算符简写形式
旧式风格:

echo $a ? $a : "No Value";
Copy after login

可简写成:

echo $a ?: "No Value";
Copy after login

即如果省略三元运算符的第二个部分,会默认用第一个部分代替。

Phar

Phar即PHP Archive, 起初只是Pear中的一个库而已,后来在PHP5.3被重新编写成C扩展并内置到 PHP 中。
Phar用来将多个 .php 脚本打包(也可以打包其他文件)成一个 .phar 的压缩文件(通常是ZIP格式)。
目的在于模仿 Java 的 .jar, 不对,目的是为了让发布PHP应用程序更加方便。同时还提供了数字签名验证等功能。
.phar 文件可以像 .php 文件一样,被PHP引擎解释执行,同时你还可以写出这样的代码来包含(require) .phar 中的代码:

require("xxoo.phar");require("phar://xxoo.phar/xo/ox.php");
Copy after login

更多信息请参见官网 [注].
注:http://www.php.net/manual/zh/phar.using.intro.php

PHP5.4(2012-2013)

Short Open Tag
Short Open Tag 自 PHP5.4 起总是可用。
在这里集中讲一下有关 PHP 起止标签的问题。即:

<?php
// Code...  何问起 hovertree.com
?>
Copy after login

通常就是上面的形式,除此之外还有一种简写形式:

<? /* Code... */ ?>
Copy after login

还可以把

<?php echo $xxoo;?>
Copy after login

简写成:

<?= $xxoo;?>
Copy after login

这种简写形式被称为 Short Open Tag, 在 PHP5.3 起被默认开启,在 PHP5.4 起总是可用。
使用这种简写形式在 HTML 中嵌入 PHP 变量将会非常方便。

对于纯 PHP 文件(如类实现文件), PHP 官方建议顶格写起始标记,同时 省略 结束标记。
这样可以确保整个 PHP 文件都是 PHP 代码,没有任何输出,否则当你包含该文件后,设置 Header 和 Cookie 时会遇到一些麻烦 [注].

注:Header 和 Cookie 必须在输出任何内容之前被发送。

数组简写形式
这是非常方便的一项特征!

// 原来的数组写法
$arr = array("key" => "value", "key2" => "value2");
// 简写形式
$arr = ["key" => "value", "key2" => "value2"];
// 何问起 hovertree.com
Copy after login

Traits
所谓Traits就是“构件”,是用来替代继承的一种机制。PHP中无法进行多重继承,但一个类可以包含多个Traits.

// Traits不能被单独实例化,只能被类所包含
trait SayWorld
{
    public function sayHello()
    {
        echo 'World!';
    }
}
class MyHelloWorld
{
    // 将SayWorld中的成员包含进来
    use SayWorld;
}
$xxoo = new MyHelloWorld();
// sayHello() 函数是来自 SayWorld 构件的
$xxoo->sayHello();
Copy after login

Traits还有很多神奇的功能,比如包含多个Traits, 解决冲突,修改访问权限,为函数设置别名等等。
Traits中也同样可以包含Traits. 篇幅有限不能逐个举例,详情参见官网 [注].
注:http://www.php.net/manual/zh/language.oop5.traits.php

内置 Web 服务器
PHP从5.4开始内置一个轻量级的Web服务器,不支持并发,定位是用于开发和调试环境。
在开发环境使用它的确非常方便。

php -S localhost:8000
Copy after login

这样就在当前目录建立起了一个Web服务器,你可以通过 http://localhost:8000/ 来访问。
其中localhost是监听的ip,8000是监听的端口,可以自行修改。

很多应用中,都会进行URL重写,所以PHP提供了一个设置路由脚本的功能:

php -S localhost:8000 index.php
Copy after login

这样一来,所有的请求都会由index.php来处理。
你还可以使用 XDebug 来进行断点调试。

细节修改
PHP5.4 新增了动态访问静态方法的方式:

$func = "funcXXOO";
A::{$func}();
Copy after login

新增在实例化时访问类成员的特征:

(new MyClass)->xxoo();
Copy after login

新增支持对函数返回数组的成员访问解析(这种写法在之前版本是会报错的):

print func()[0];
Copy after login

PHP5.5(2013起)

yield
yield关键字用于当函数需要返回一个迭代器的时候, 逐个返回值。

function number10()
{    for($i = 1; $i <= 10; $i += 1)
        yield $i;
}
Copy after login

该函数的返回值是一个数组:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy after login

list() 用于 foreach
可以用 list() 在 foreach 中解析嵌套的数组:

$array = [
    [1, 2, 3],
    [4, 5, 6],
];
foreach ($array as list($a, $b, $c))
    echo "{$a} {$b} {$c}
";
Copy after login

结果:

1 2 3
4 5 6
Copy after login

细节修改
不推荐使用 mysql 函数,推荐使用 PDO 或 MySQLi, 参见前文。
不再支持Windows XP.
可用 MyClass::class 取到一个类的完整限定名(包括命名空间)。
empty() 支持表达式作为参数。
try-catch 结构新增 finally 块。

PHP5.6

更好的常量
定义常量时允许使用之前定义的常量进行计算:

const A = 2;
const B = A + 1;
class C
{
    const STR = "hello";
    const STR2 = self::STR + ", world";
}
Copy after login

允许常量作为函数参数默认值:

function func($arg = C::STR2)
Copy after login

更好的可变函数参数
用于代替 func_get_args()

function add(...$args)
{
    $result = 0;
    foreach($args as $arg)
        $result += $arg;
    return $result;
}// 何问起 hovertree.com
Copy after login

同时可以在调用函数时,把数组展开为函数参数:// 结果为 6
命名空间
命名空间支持常量和函数:

namespace NameSpace {
    const FOO = 42;
    function f() { echo __FUNCTION__."
"; }
}
namespace {
    use const NameSpaceFOO;
    use function NameSpacef;
    echo FOO."
";
    f();
}
Copy after login

推荐学习:《PHP视频教程

Related labels:
source:zoukankan
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!