PHP 5.2, 5.3, 5.4, 5.5, 5.6 version comparison and new features detailed

Source: Internet
Author: User
Tags autoload class definition deprecated finally block spl safe mode traits least privilege

As of Now (2015.1), the latest stable version of PHP is PHP5.5, but almost half of the users are still using PHP5.2, which is already out of maintenance, and half of the remaining users are using PHP5.3.
Because PHP that "set hundred of the length" of the egg pain grammar, coupled with the community atmosphere is not good, many people on the new version, new features are not interested.
This article will describe the new features that have been added since PHP5.2 until PHP5.6.

    • 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 bindings, Heredoc and Nowdoc, const, ternary operators, Phar
    • Php5.4:short Open Tag, array shorthand form, Traits, built-in Web server, detail modified
    • Php5.5:yield, List () for foreach, detail modification
    • PHP5.6: constant enhancement, variable function parameters, namespace enhancement

Note: The support was discontinued in January 2011:
Note: Http://

PHP5.2 ago

(2006 ago)
By the way, the features that PHP5.2 has been presented but worth introducing.


As you may know, the __autoload () function, if defined, is called when an undefined class is used in the code, and you can load the corresponding class implementation file in the function, such as:

function __autoload ($classname) {    require_once ("{$classname}.php")}

However, this function is not recommended because only one such __autoload () function can be found in a project because PHP does not allow the name of the function. But when you use some class libraries, there will inevitably be multiple autoload functions, so Spl_autoload_register () instead:

Spl_autoload_register (function ($classname) {    require_once ("{$classname}.php")});

Spl_autoload_register () registers a function in the list of AutoLoad functions, and when an undefined class is present, SPL [note] invokes the registered AutoLoad function one at a time in reverse order, which means that you can use Spl_ Autoload_register () registers multiple autoload functions.

Note: Spl:standard PHP library, standard PHP libraries, is designed to solve some classic problems (such as data structures).

PDO and Mysqli

That is, PHP data object, PHP, which is the new database access interface of PHP.

In the traditional style, access to the MySQL database should look like this:

Connect to the server, select database $conn = mysql_connect ("localhost", "User", "password"), mysql_select_db ("database");//execute SQL query $type = $_ post[' type ']; $sql = "select * from ' table ' WHERE ' type ' = {$type}"; $result = mysql_query ($sql);//print result while ($row = Mysql_f Etch_array ($result, Mysql_assoc) {    foreach ($row as $k => $v)        print "{$k}: {$v}\n";} Release the result set, close the connection mysql_free_result ($result); Mysql_close ($conn);

To be able to make the code implement database-independent, that is, a piece of code for a variety of databases (for example, the above code only for MySQL), PHP officially designed PDO.
In addition to this, PDO offers more features, such as:

    • Object-oriented style interface
    • SQL Precompilation (prepare), placeholder syntax
    • Higher execution efficiency, as an official recommendation, with special performance optimizations
    • Support for most SQL databases, change of database without code changes

The above code will be implemented in PDO:

Connect to database $conn = new PDO ("Mysql:host=localhost;dbname=database", "User", "password");//precompiled SQL, binding parameter $query = $conn-& Gt;prepare ("SELECT * from ' table ' WHERE ' type ' =: type '); $query->bindparam (" type ", $_post[' type ']);// Executes the query and prints the result foreach ($query->execute () as $row) {    foreach ($row as $k => $v)        print "{$k}: {$v}\n";}

PDO is an officially recommended, more generic way to access your database, and if you don't have special needs, then you'd better learn and use PDO.
But if you need to use the advanced features that are unique to MySQL, you might want to try Mysqli, because PDO does not include features that are unique to MySQL in order to be able to use it on multiple databases at the same time.

MYSQLI is an enhanced interface for MySQL, providing both process-oriented and object-oriented interfaces, as well as the currently recommended MySQL driver, and the old C-style MySQL interface will be turned off by default in the future.
There are not many new concepts in the usage of mysqli compared to the above two pieces of code, which are no longer presented here, and can be found in the PHP official website documentation [note].


Type constraints

Type constraints allow you to limit the type of a parameter, but this mechanism is imperfect, and currently applies only to classes and callable (executable types), and to Array (arrays), not to string and int.

Limit the first parameter to MyClass, the second argument to the executable type, and the third parameter to the array function MyFunction (MyClass $a, callable $b, array $c) {    //...}


JSON Support

including Json_encode (), Json_decode () and other functions, JSON is a very popular data interchange format in the WEB domain, can be directly supported by JS, JSON is actually part of the JS syntax.
JSON series functions, you can convert the structure of an array in PHP to a JSON string:

$array = ["Key" => "Value", "Array" => [1, 2, 3, 4]]; $json = Json_encode ($array), echo "{$json}\n"; $object = Json_decode ($json);p rint_r ($object);


{"Key": "Value", "array": [1,2,3,4]}stdclass Object (    [key] => value    [array] => Array        (            [0] => 1            [1] => 2            [2] => 3            [3] => 4        ))

It is important to note that Json_decode () returns an object instead of an array by default, and if it is necessary to return an array, set the second argument to true.



PHP5.3 is a very big update, adding a lot of new features, but also made some non-compatible changes.

Deprecated features

The following features are deprecated and, if enabled in the configuration file, PHP warns you at runtime.

Register Globals

This is an option in php.ini (register_globals), which registers all form variables ($_get and $_post) as global variables when turned on.
Look at the following example:

if (Isauth ())    $authorized = true;if ($authorized)    include ("page.php");

This code sets the $authorized to True when it passes validation. The page is then determined based on the value of the $authorized.

However, since the $authorized is not initialized to false beforehand, when Register_globals is opened, it is possible to access/auth.php?authorized=1 to define the value of the variable, bypassing the authentication.

This feature is a legacy issue, which is closed by default in PHP4.2 and removed in PHP5.4.

Magic Quotes

corresponding to the option MAGIC_QUOTES_GPC in php.ini, this feature is also a legacy issue that has been removed in PHP5.4.

This feature escapes all user input, which looks good, and in the first chapter we talked about escaping user input.
However, PHP does not know which inputs will go into SQL, which input will go into the Shell, and which inputs will be displayed as HTML, so this escape can cause confusion in many cases.

Safe Mode

Many virtual hosting providers use Safe mode to isolate multiple users, but safe mode has many problems, such as some extensions that do not follow Safe mode for permission control.
PHP officially recommends using the operating system mechanism for permission isolation, allowing the Web server to run the PHP interpreter with different user rights, see the principle of least privilege in Chapter I.

anonymous functions

Also known as closures (Closures), is often used to temporarily create a nameless function for use in callback functions.

$func = function ($arg) {    print $arg;}; $func ("Hello World");

The code above defines an anonymous function and assigns a value to the $func.
You can see that defining an anonymous function still uses the function keyword, except that it omits the name and is directly a parameter list.

Then we call the anonymous function stored in the $func.

Anonymous functions can also capture external variables with the USE keyword:

function Arrayplus ($array, $num) {    array_walk ($array, function (& $v) use ($num) {        $v + = $num;    });}

The above code defines a arrayplus () function (which is not an anonymous function), which adds each item in an array ($array) with a specified number ($num).

In the implementation of Arrayplus (), we used the Array_walk () function, which executes a callback function for each item of an array, which is the anonymous function we define.
After the argument list of the anonymous function, we use the Using keyword to snap the $num outside of the anonymous function into the function to know exactly how much to add.

Magic method: __invoke (), __callstatic ()

In the object-oriented architecture of PHP, a number of "magic methods" are provided to implement "overloads" similar to those in other languages, such as triggering a magic method when accessing a nonexistent property or method.

With the addition of anonymous functions, PHP introduces a new Magic Method __invoke ().
The Magic method is called when an object is called as a function:

Class a{public    function __invoke ($str)    {        print "A::__invoke (): {$str}";}    } $a = new A; $a ("Hello world");

The output is undoubtedly:

A::__invoke (): Hello World

__callstatic () is called when a static method that does not exist is called.

Name space

PHP's namespace has the most unprecedented egg-aching syntax:

<? The delimiter for the php//namespace is a backslash, and the declaration statement must be on the first line of the file. Namespaces can contain arbitrary code, but only * * classes, Functions, constants * * are affected by the namespace. Namespace xxoo\test;//the fully qualified name of the class is \xxoo\test\a, where the first backslash represents the global namespace. Class a{}//You can also define a second namespace in an already file, and the next code will be in \other\test2. Namespace other\test2;//instantiates objects from other namespaces: $a = new \xxoo\test\a; Class b{}//You can also define a third namespace with curly braces namespace other {    //Instantiate an object from a child namespace:    $b = new test2\b;    Import names from other namespaces, rename them,    //Note that only classes can be imported and cannot be used for functions and constants. Use    \xxoo\test\a as ClassA}

For more information about namespaces, see the official website [note].

Namespaces are often used in conjunction with AutoLoad to automatically load class implementation files:

Spl_autoload_register (    function ($class) {        spl_autoload (str_replace ("\ \", "/", $class));    });

When you instantiate a class \xxoo\test\a, the fully qualified name of the class is passed to the AutoLoad function, and the AutoLoad function replaces the namespace delimiter (backslash) in the class name with a slash and contains the corresponding file.
This enables class definition file classification to be stored and loaded automatically on demand.


Late static binding

PHP's OPP mechanism, with inheritance and similar virtual functions, such as the following code:

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 ();

The output is:


As you can see, when you use $this->funcxxoo () in a, the mechanism that embodies the "virtual function" is actually called B::funcxxoo ().
However, if all functions are changed to static functions:

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 ();

The situation is not so optimistic, the output is:

A::funcxxoo ()

This is because the semantics of self are inherently "current class", so PHP5.3 gives a new feature to the static keyword: late static binding:

Class a{    static public Function Callfuncxxoo ()    {        print static::funcxxoo ();    }    // ...} // ...

This will output as expected:

Heredoc and Nowdoc

PHP5.3 has made some improvements to Heredoc and Nowdoc, all of which are used to embed large strings in PHP code.

The behavior of Heredoc is similar to a double-quote string:

$name = "MyName"; Echo <<< Textmy name is "{$name}". TEXT;

Heredoc begins with three left angle brackets followed by an identifier (TEXT) until an identifier of the same shelf (not indented) ends.
Just like a double-quoted string, where you can embed a variable.

Heredoc can also be used for function parameters, as well as for class member initialization:

Var_dump (<<< Eodhello Worldeod); class a{    const XX = <<< Eodhello Worldeod;    Public $oo = <<< Eodhello Worldeod;}

Nowdoc behaves like a single-quote string, where a variable cannot be embedded, and Heredoc the only difference is that the identifiers after three left angle brackets are enclosed in single quotes:

$name = "MyName"; Echo <<< ' TEXT ' My name is ' {$name} '. TEXT;


My name is "{$name}".
Defining constants with Const

PHP5.3 also supports the use of Const definition constants in global namespaces and classes.

Old Style:

Define ("Xooo", "Value");

New style:

Const XXOO = "Value";

The const form applies only to constants, not to expressions that can be evaluated at run time:

Correct const XXOO = 1234;//Error Const XXOO = 2 * 617;
Abbreviated form of ternary operator

Old Style:

echo $a? $a: "No Value";

Can be written as:

echo $a?: "No Value";

That is, if the second part of the ternary operator is omitted, the first part is replaced by default.


Phar, PHP Archive, was originally just a library in pear, and later was rewritten as a C extension in PHP5.3 and built into PHP.
Phar is used to package multiple. PHP scripts (or to package other files) into a. Phar Compressed file (usually in zip format).
The goal is to mimic Java's. jar, which is wrong, to make it easier to publish PHP applications. It also provides features such as digital signature verification.

The. Phar file can be interpreted by the PHP engine as if it were a. php file, and you can also write code to contain (require) the code in Phar:

Require ("Xxoo.phar"); Require ("phar://xxoo.phar/xo/ox.php");

For more information, please see the official website [note].




Short Open Tag

The short Open Tag is always available from PHP5.4.
Focus on the issue of PHP start and end tags here. That

<? php//Code ...? >

This is usually the form above, in addition to a shorthand form:

<? /* Code ... */?>

can also put

<? php echo $xxoo;? >

Jane writes:

<? = $xxoo;? >

This shorthand form, known as the short open Tag, is turned on by default at PHP5.3 and is always available at PHP5.4.
It is very convenient to embed PHP variables in HTML in this shorthand form.

For pure PHP files (such as class implementation files), PHP officially recommends shelf write the start tag, while omitting the end tag.
This ensures that the entire PHP file is PHP code, without any output, or you will encounter some trouble setting the Header and Cookie when you include the file [note].

Note: Headers and cookies must be sent before any content is output.

Array Shorthand form

This is a very handy feature!

The original array notation $arr = Array ("Key" => "Value", "Key2" => "value2");//Shorthand form $arr = ["Key" => "Value", "Key2" => "Value2"];

The so-called traits is the "component", which is a mechanism to replace inheritance. Multiple inheritance is not possible in PHP, but a class can contain multiple traits.

Traits cannot be instantiated separately, only the class contains trait sayworld{public    function SayHello ()    {        echo ' world! ';    }} Class myhelloworld{    //The members in the Sayworld are included in the use    Sayworld;} $xxoo = new Myhelloworld ();//SayHello () function is $xxoo->sayhello () from Sayworld component;

Traits also has many magical features, such as including multiple traits, resolving conflicts, modifying access rights, setting aliases for functions, and so on.
The traits can also contain traits. Limited space is not an example, please refer to the official website [note].


Built-in Web server

PHP starts with a 5.4 built-in lightweight Web server, does not support concurrency, and is used for development and debugging environments.

It is really handy to use it in the development environment.

Php-s localhost:8000

This creates a Web server in the current directory that you can access through http://localhost:8000/.
Where localhost is the listening ip,8000 is the listening port, can be modified by itself.

In many applications, url rewriting is done, so PHP provides a function to set up a routing script:

Php-s localhost:8000 index.php

In this way, all requests are handled by index.php.

You can also use XDebug to debug breakpoints.

Details modification

PHP5.4 adds a way to dynamically access static methods:

$func = "Funcxxoo"; a::{$func} ();

New features that access class members when instantiated:

(New MyClass)->xxoo ();

Added support for member access parsing of function return arrays (this is an error in previous versions):

print func () [0];

(from 2013)


The yield keyword is used to return values one at a time when the function needs to return an iterator.

function Number10 () {for    ($i = 1; $i <=; $i + = 1)        yield $i;}

The return value of the function is an array:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List () for foreach

Nested arrays can be parsed in foreach using List ():

$array = [    [1, 2, 3],    [4, 5, 6],];foreach ($array as List ($a, $b, $c))    echo "{$a} {$b} {$c}\n";


Details modification

It is not recommended to use the MySQL function, PDO or mysqli is recommended, see the previous article.
Windows XP is no longer supported.

You can use Myclass::class to fetch the fully qualified name of a class, including the namespace.

Empty () supports expressions as arguments.

The TRY-CATCH structure adds a finally block.

PHP5.6 a Better constant

Defining constants allows calculations using constants defined previously:

Const A = 2;const B = A + 1;class c{    const STR = "Hello";    Const STR2 = Self::str + ", World";}

Allow constants as default values for function parameters:

function func ($arg = c::str2)
Better variable function parameters

Used instead of Func_get_args ()

function Add (... $args) {    $result = 0;    foreach ($args as $arg)        $result + = $arg;    return $result;}

You can also expand the array to function parameters when calling the function:

$arr = [2, 3];add (1, ... $arr);//Result 6
Name space

Namespaces support constants and functions:

namespace Name\space {    const FOO =;    function f () {echo __function__. \ n "; }}namespace {use    const name\space\foo;    Use function name\space\f;    echo FOO. " \ n ";    f ();}

PHP 5.2, 5.3, 5.4, 5.5, 5.6 version comparison and new features detailed

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.