


Detailed explanation of the differences between various versions of PHP
截至目前(2015.1), PHP 的最新稳定版本是 PHP5.5, 但有差不多一半的用户仍在使用已经不在维护 的 PHP5.2, 其余的一半用户在使用 PHP5.3 .因为 PHP 那“集百家之长”的蛋疼语法,加上社区氛围不好,很多人对新版本,新特征并无兴趣。
本文将会介绍自 PHP5.2 起,直至 PHP5.6 中增加的新特征。
PHP5.2 以前:autoload, PDO 和 MySQLi, 类型约束
PHP5.2:JSON 支持
PHP5.3:弃用的功能,匿名函数,新增魔术方法,命名空间,后期静态绑定,Heredoc 和 Nowdoc, const, 三元运算符,Phar
PHP5.4:Short Open Tag, 数组简写形式,Traits, 内置 Web 服务器,细节修改
PHP5.5:yield, list() 用于 foreach, 细节修改
PHP5.6: 常量增强,可变函数参数,命名空间增强
注:已于2011年1月停止支持: http://www.php.net/eol.php
注:http://w3techs.com/technologies/details/pl-php/5/all
PHP5.2以前
(2006前)
顺便介绍一下 PHP5.2 已经出现但值得介绍的特征。
autoload
大家可能都知道 __autoload() 函数,如果定义了该函数,那么当在代码中使用一个未定义的类的时候,该函数就会被调用,你可以在该函数中加载相应的类实现文件,如:
function __autoload($classname) { require_once("{$classname}.php") }
但该函数已经不被建议使用,原因是一个项目中仅能有一个这样的 __autoload() 函数,因为 PHP 不允许函数重名。但当你使用一些类库的时候,难免会出现多个 autoload 函数的需要,于是 spl_autoload_register() 取而代之:
spl_autoload_register(function($classname) { require_once("{$classname}.php") });
spl_autoload_register() 会将一个函数注册到 autoload 函数列表中,当出现未定义的类的时候,SPL [注] 会按照注册的倒序逐个调用被注册的 autoload 函数,这意味着你可以使用 spl_autoload_register() 注册多个 autoload 函数.
注:SPL: Standard PHP Library, 标准 PHP 库, 被设计用来解决一些经典问题(如数据结构).
PDO 和 MySQLi
即 PHP Data Object, PHP 数据对象,这是 PHP 的新式数据库访问接口。
按照传统的风格,访问 MySQL 数据库应该是这样子:
// 连接到服务器,选择数据库 $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}\n"; } // 释放结果集,关闭连接 mysql_free_result($result); mysql_close($conn);
为了能够让代码实现数据库无关,即一段代码同时适用于多种数据库(例如以上代码仅仅适用于MySQL),PHP 官方设计了 PDO.
除此之外,PDO 还提供了更多功能,比如:
面向对象风格的接口
SQL预编译(prepare), 占位符语法
更高的执行效率,作为官方推荐,有特别的性能优化
支持大部分SQL数据库,更换数据库无需改动代码
上面的代码用 PDO 实现将会是这样:
// 连接到数据库 $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}\n"; }
PDO 是官方推荐的,更为通用的数据库访问方式,如果你没有特殊需求,那么你最好学习和使用 PDO.
但如果你需要使用 MySQL 所特有的高级功能,那么你可能需要尝试一下 MySQLi, 因为 PDO 为了能够同时在多种数据库上使用,不会包含那些 MySQL 独有的功能。
MySQLi 是 MySQL 的增强接口,同时提供面向过程和面向对象接口,也是目前推荐的 MySQL 驱动,旧的C风格 MySQL 接口将会在今后被默认关闭。
MySQLi 的用法和以上两段代码相比,没有太多新概念,在此不再给出示例,可以参见 PHP 官网文档 [注]。
注:http://www.php.net/manual/en/mysqli.quickstart.php
类型约束
通过类型约束可以限制参数的类型,不过这一机制并不完善,目前仅适用于类和 callable(可执行类型) 以及 array(数组), 不适用于 string 和 int.
// 限制第一个参数为 MyClass, 第二个参数为可执行类型,第三个参数为数组 function MyFunction(MyClass $a, callable $b, array $c) { // ... }
PHP5.2
(2006-2011)
JSON 支持
包括 json_encode(), json_decode() 等函数,JSON 算是在 Web 领域非常常用的数据交换格式,可以被 JS 直接支持,JSON 实际上是 JS 语法的一部分。
JSON 系列函数,可以将 PHP 中的数组结构与 JSON 字符串进行转换:
$array = ["key" => "value", "array" => [1, 2, 3, 4]]; $json = json_encode($array); echo "{$json}\n"; $object = json_decode($json); print_r($object);
输出:
{"key":"value","array":[1,2,3,4]} stdClass Object ( [key] => value [array] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) )
值得注意的是 json_decode() 默认会返回一个对象而非数组,如果需要返回数组需要将第二个参数设置为 true.
PHP5.3
(2009-2012)
PHP5.3 算是一个非常大的更新,新增了大量新特征,同时也做了一些不向下兼容的修改。
弃用的功能
以下几个功能被弃用,若在配置文件中启用,则 PHP 会在运行时发出警告。
Register Globals
这是 php.ini 中的一个选项(register_globals), 开启后会将所有表单变量(GET和GET和_POST)注册为全局变量.
看下面的例子:
if(isAuth()) $authorized = true; if($authorized) include("page.php");
这段代码在通过验证时,将 authorized设置为true.然后根据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解释器,请参见第一章中的最小权限原则.
匿名函数
也叫闭包(Closures), 经常被用来临时性地创建一个无名函数,用于回调函数等用途。
$func = function($arg) { print $arg; }; $func("Hello World");
以上代码定义了一个匿名函数,并赋值给了 $func.
可以看到定义匿名函数依旧使用 function 关键字,只不过省略了函数名,直接是参数列表。
然后我们又调用了 $func 所储存的匿名函数。
匿名函数还可以用 use 关键字来捕捉外部变量:
function arrayPlus($array, $num) { array_walk($array, function(&$v) use($num){ $v += $num; }); }
上面的代码定义了一个 arrayPlus() 函数(这不是匿名函数), 它会将一个数组(array)中的每一项,加上一个指定的数字(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");
输出毫无疑问是:
A::__invoke(): Hello World
__callStatic() 则会在调用一个不存在的静态方法时被调用。
命名空间
PHP的命名空间有着前无古人后无来者的无比蛋疼的语法:
7944b44fbccfb3eb84b6eb45f60a66b7
通常就是上面的形式,除此之外还有一种简写形式:
<? /* Code... */ ?>
还可以把
<?php echo $xxoo;?>
简写成:
<?= $xxoo;?>
这种简写形式被称为 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"];
Traits
所谓Traits就是“构件”,是用来替代继承的一种机制。PHP中无法进行多重继承,但一个类可以包含多个Traits.
// Traits不能被单独实例化,只能被类所包含 trait SayWorld { public function sayHello() { echo 'World!'; } } class MyHelloWorld { // 将SayWorld中的成员包含进来 use SayWorld; } $xxoo = new MyHelloWorld(); // sayHello() 函数是来自 SayWorld 构件的 $xxoo->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 新增了动态访问静态方法的方式:
$func = "funcXXOO"; A::{$func}();
新增在实例化时访问类成员的特征:
(new MyClass)->xxoo();
新增支持对函数返回数组的成员访问解析(这种写法在之前版本是会报错的):
print func()[0];
PHP5.5
(2013起)
yield
yield关键字用于当函数需要返回一个迭代器的时候, 逐个返回值。
function number10() { for($i = 1; $i <= 10; $i += 1) yield $i; }
该函数的返回值是一个数组:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list() 用于 foreach
可以用 list() 在 foreach 中解析嵌套的数组:
$array = [ [1, 2, 3], [4, 5, 6], ]; foreach ($array as list($a, $b, $c)) echo "{$a} {$b} {$c}\n";
结果:
细节修改
不推荐使用 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"; }
允许常量作为函数参数默认值:
function func($arg = C::STR2)
更好的可变函数参数
用于代替 func_get_args()
function add(...$args) { $result = 0; foreach($args as $arg) $result += $arg; return $result; }
同时可以在调用函数时,把数组展开为函数参数:
$arr = [2, 3]; add(1, ...$arr); // 结果为 6
命名空间
命名空间支持常量和函数:
namespace Name\Space { const FOO = 42; function f() { echo __FUNCTION__."\n"; } } namespace { use const Name\Space\FOO; use function Name\Space\f; echo FOO."\n"; f(); }
相关推荐:
The above is the detailed content of Detailed explanation of the differences between various versions of PHP. For more information, please follow other related articles on the PHP Chinese website!

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.