PHP 5.3 ~ PHP 5.6 功能变动

PHP 5.3 ~ PHP 5.6 功能变动

本文将会介绍自 PHP 5.3 起,直至 PHP 5.6 中增加/删除/更改的特征。

总纲

PHP 5.3以前:autoload,PDO 和 MySQLi,类型约束,JSON 支持,Phar支持,……

PHP5.3:匿名函数,新增魔术方法,命名空间,后期静态绑定,Heredoc 和 Nowdoc, const, 三元运算符,……

PHP5.4:Short Open Tag, 数组简写形式,Traits, 内置 Web 服务器,……

PHP5.5:yield, list() 用于 foreach, ……

PHP5.6: 常量增强,可变函数参数,命名空间增强,……

PHP 5.3以前

类型约束

通过类型约束可以限制参数的类型,不过这一机制并不完善,目前仅适用于类、接口、 array(数组,从PHP 5.1开始)、callable(可执行类型,从PHP 5.4开始) 以及string 和 int(从PHP 7.0开始).(http://php.net/manual/zh/language.oop5.typehinting.php)

JSON 支持

包括 json_encode(), json_decode() 等函数,JSON 系列函数,可以将 PHP 中的数组结构与 JSON 字符串进行转换。值得注意的是 json_decode() 默认会返回一个对象而非数组,如果需要返回数组需要将第二个参数设置为 true.

Phar支持

http://php.net/manual/zh/phar.requirements.php

PHP 5.3

PHP 5.3 算是一个非常大的更新,新增了大量新特征,同时也做了一些不向下兼容的修改。

New furtures

Added lambda functions and closures.

Added “jump label” operator (limited “goto”).

Added NOWDOC syntax.

Added HEREDOC syntax with double quotes.

Added “?:” operator.

Added support for namespaces.

Added support for Late Static Binding.

(后期静态绑定 http://php.net/manual/en/language.oop5.late-static-bindings.php

Added support for __callStatic() magic method.则会在调用一个不存在的静态方法时被调用。

Added forward_static_call(_array) to complete LSB.

Added support for dynamic access of static members using $foo::myFunc().

Added __DIR__ constant.

Added new error modes E_USER_DEPRECATED and E_DEPRECATED. E_DEPRECATED is used to inform about stuff being scheduled for removal in future PHP versions.

Added “request_order” INI variable to control specifically $_REQUEST behavior.

Added ability to handle exceptions in destructors.

Allowed using full path to load modules using “extension” directive.

Added Enchant extension as a way to access spell checkers.

Added fileinfo extension as replacement for mime_magic extension.

Added intl extension for Internationalization.

Added mysqlnd extension as replacement for libmysql for ext/mysql, mysqli and PDO_mysql.(why?http://blog.csdn.net/dragon8299/article/details/6273295

Added phar extension for handling PHP Archives.

Added SQLite3 extension.

新增魔术方法__invoke() (当尝试以调用函数的方式调用一个对象时,__invoke() 方法会被自动调用)

<?php
class CallableClass
{
function 
__invoke($x) {
var_dump($x);
}
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));

Outputint(5)

bool(true)

Heredoc 和 Nowdoc

PHP5.3 对 Heredoc 以及 Nowdoc 进行了一些改进,它们都用于在 PHP 代码中嵌入大段字符串。

Heredoc 的行为类似于一个双引号字符串:

$name = “MyName”;

echo <<< TEXT

My name is “{$name}”.

TEXT;

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

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

var_dump(<<<EOD

Hello World

EOD

);

class A {

const xx = <<< EOD

Hello World

EOD;

public $oo = <<< EOD

Hello World

EOD;

}

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

$name = “MyName”;

echo <<< ‘TEXT’

My name is “{$name}”.

TEXT;

//output  My name is “{$name}”.

Deprecated features

Deprecated session_register(), session_unregister() and session_is_registered().

Deprecated define_syslog_variables().

Deprecated ereg extension.

Register Globals在PHP 5.3中被废弃,在PHP 5.4中被移除。(从PHP 4.2开始被默认关闭,http://php.net/manual/en/security.globals.php)

Magic Quotes has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. (对应 php.ini 中的选项 magic_quotes_gpc http://php.net/manual/en/security.magicquotes.php)

Safe Mode has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. ( http://php.net/manual/en/features.safe-mode.php)

Changed

Changed property_exists() to check the existence of a property independent of accessibility (like method_exists()).

 

PHP 5.4

New furtures

Short Open Tag

<?= is now always available regardless of the short_open_tag setting.

<?php echo “hello world”;?> ==>  <? echo “hello world”; ?>

<?php echo $xxoo;?> ==> <?= $xxoo;?>

这种简写形式被称为 Short Open Tag, 在 PHP5.3 起被默认开启,在 PHP5.4 起总是可用。

Added short array syntax support

Added short array syntax support ([1,2,3]) 支持数组简写语法

// 原来的数组写法

$arr = array(“key” => “value”, “key2” => “value2”);

// 简写形式

$arr = [“key” => “value”, “key2” => “value2”];

Traits

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

Traits还有很多神奇的功能,比如包含多个Traits, 解决冲突,修改访问权限,为函数设置别名等等。Traits中也同样可以包含Traits (http://www.php.net/manual/zh/language.oop5.traits.php)

内置 Web 服务器

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

php -S localhost:8000

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

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

php -S localhost:8000 index.php

Closures now support $this

The session extension can now track the upload progress of files.

Removed legacy features

break/continue $var syntax.

Safe mode and all related ini options.

register_globals and register_long_arrays ini options.

import_request_variables().

allow_call_time_pass_reference.

define_syslog_variables ini option and its associated function.

highlight.bg ini option.

Session bug compatibility mode (session.bug_compat_42 and session.bug_compat_warn ini options).

session_is_registered(), session_register() and session_unregister() functions.

y2k_compliance ini option.

magic_quotes_gpc, magic_quotes_runtime and magic_quotes_sybase ini options. get_magic_quotes_gpc, get_magic_quotes_runtime are kept but always return false, set_magic_quotes_runtime raises an E_CORE_ERROR.

Removed support for putenv(“TZ=..”) for setting the timezone.

Removed the timezone guessing algorithm in case the timezone isn’t set with date.timezone or date_default_timezone_set(). Instead of a guessed timezone, “UTC” is now used instead.

Changed

Changed E_ALL to include E_STRICT.

Changed default value of “default_charset” php.ini option from ISO-8859-1 to UTF-8.

Added class member access on instantiation (e.g. (new foo)->bar()) support.

PHP5.4 新增了动态访问静态方法的方式:$func = “funcXXOO”;  A::{$func}();

新增在实例化时访问类成员的特征:(new MyClass)->xxoo();

新增支持对函数返回数组的成员访问解析(这种写法在PHP 5.3中会报错的):print func()[0];

In the date and time extension, the timezone can no longer be set using the TZ environment variable. Instead you have to specify a timezone using the date.timezone php.ini option or date_default_timezone_set() function. PHP will no longer attempt to guess the timezone, and will instead fall back to “UTC” and issue a E_WARNING.

Non-numeric string offsets – e.g. $a[‘foo’] where $a is a string – now return false on isset() and true on empty(), and produce a E_WARNING if you try to use them. Offsets of types double, bool and null produce a E_NOTICE. Numeric strings (e.g. $a[‘2’]) still work as before. Note that offsets like ‘12.3’ and ‘5 foobar’ are considered non-numeric and produce a E_WARNING, but are converted to 12 and 5 respectively, for backward compatibility reasons. Note: Following code returns different result. $str=’abc’;var_dump(isset($str[‘x’])); // false for PHP 5.4 or later, but true for 5.3 or less

The following keywords are now reserved, and may not be used as names by functions, classes, etc.

trait

callable

insteadof

http://php.net/manual/en/language.oop5.traits.php

 

PHP 5.5

New furtures

yield

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

function number10() {

for($i = 1; $i <= 10; $i += 1)

yield $i;

}

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

list() 用于 foreach

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

$array = [

[1, 2, 3],

[4, 5, 6],

];

foreach ($array as list($a, $b, $c)){

echo “{$a} {$b} {$c}\n”;

}

output:

1 2 3

4 5 6

MyClass::class

可用 MyClass::class 取到一个类的完整限定名(包括命名空间)。例如:\namespacename\UserController::class

finally keyword

try-catch 结构新增 finally 块。

New password hashing API

A new password hashing API that makes it easier to securely hash and manage passwords using the same underlying library as crypt() in PHP has been added. See the documentation for password_hash() for more detail.

http://php.net/manual/en/function.password-hash.php

array and string literal dereferencing

OPcache extension added

Apache 2.4 handler supported on Windows

Deprecated featuress

不推荐使用 mysql 函数,推荐使用 PDO 或 MySQLi

不再支持Windows XP

Removed legacy features:

Remove php_logo_guid(), php_egg_logo_guid(), php_real_logo_guid(), zend_logo_guid()

Drop Windows XP and 2003 support

Changed

empty() 支持表达式作为参数。

 

PHP5.6

New furtures

Added constant scalar expressions syntax.

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

const A = 2;

const B = A + 1;

class C {

const STR = “hello”;

const STR2 = self::STR + “, world”;

}

允许常量作为函数参数默认值:function func($arg = C::STR2)

Added an exponentiation operator (**).

$a ** $b Exponentiation(取幂;乘方)   Result of raising $a to the $b’th power. Introduced in PHP 5.6.  (10 ** 2 = 100)

更好的可变函数参数

用于代替 func_get_args()

function add(…$args) {

$result = 0;

foreach($args as $arg)

$result += $arg;

return $result;

}

同时可以在调用函数时,把数组展开为函数参数:

$arr = [2, 3];

add(1, …$arr);//output  6

Added use function and use const

The use operator has been extended to support importing functions and constants in addition to classes. This is achieved via the use function and use const constructs, respectively.

Deprecated features

$HTTP_RAW_POST_DATA and always_populate_raw_post_data

always_populate_raw_post_data will now generate an E_DEPRECATED error when $HTTP_RAW_POST_DATA is populated. New code should use php://input instead of $HTTP_RAW_POST_DATA, which will be removed in a future release. You can opt in for the new behaviour (in which $HTTP_RAW_POST_DATA is never defined hence no E_DEPRECATED error will be generated) by setting always_populate_raw_post_data to -1.

Changed

Array keys won’t be overwritten when defining an array as a property of a class via an array literal

http://php.net/manual/en/migration56.incompatible.php

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

*