"PHP History" PHP5.2 The new features in PHP5.6

Source: Internet
Author: User
Tags autoload deprecated spl traits web hosting
label:

As of now (2014.2), the latest stable version of PHP is PHP5.5, but almost half of the users are still using PHP5.2, which is no longer maintained, and the remaining half of users are using PHP5.3.

Because of PHP's "gathering of a hundred families" and its painful grammar, and the poor community atmosphere, many people are not interested in the new version and new features.

This article will introduce new features added from PHP5.2 to PHP5.6.

Before PHP5.2: autoload, PDO and MySQLi, type constraints
PHP5.2: JSON support
PHP5.3: Deprecated functions, anonymous functions, new magic methods, namespaces, late static binding, Heredoc and Nowdoc, const, ternary operator, Phar
PHP5.4: Short Open Tag, short form of array, Traits, built-in Web server, details modification
PHP5.5: yield, list () for foreach, details modification
PHP5.6: Constant enhancement, variable function parameters, namespace enhancement
Note: Support was discontinued in January 2011: http://www.php.net/eol.php

Note: http://w3techs.com/technologies/details/pl-php/5/all

 

 

Before PHP5.2

(Before 2006)

By the way, introduce the features that PHP5.2 has appeared but it is worth introducing.

 

autoload

Everyone may know the __autoload () function. If the 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 the function. Such as:

function __autoload ($ classname)
{
    require_once ("{$ classname} .php")
}
However, this function is no longer recommended because the project can only have one such __autoload () function, because PHP does not allow duplicate function names. But when you use some libraries, it is inevitable that there will be multiple autoload functions, so spl_autoload_register () replaces it:

spl_autoload_register (function ($ classname)
{
    require_once ("{$ classname} .php")
});
spl_autoload_register () will register a function in the autoload function list. When an undefined class appears, the SPL [Note] will call the registered autoload function 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, Standard PHP Library, is designed to solve some classic problems (such as data structures).

 

PDO and MySQLi

Namely PHP Data Object, PHP data object, this is PHP's new database access interface.

According to the traditional style, access to the MySQL database should be like this:

// Connect to the server and select the 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 the result
while ($ row = mysql_fetch_array ($ result, MYSQL_ASSOC))
{
    foreach ($ row as $ k => $ v)
        print "{$ k}: {$ v} \ n";
}

// Release the result set and close the connection
mysql_free_result ($ result);
mysql_close ($ conn);
In order to make the code irrelevant to the database, 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:

Object-oriented interface
SQL preparation (prepare), placeholder syntax
Higher execution efficiency, as an official recommendation, has special performance optimization
Supports most SQL databases, no code changes required to replace the database
The above code will be implemented using PDO like this:

// Connect to the database
$ conn = new PDO ("mysql: host = localhost; dbname = database", "user", "password");

// Pre-compiled SQL, bind parameters
$ query = $ conn-> prepare ("SELECT * FROM` table` WHERE `type` =: type");
$ query-> bindParam ("type", $ _POST [‘type‘]);

// execute the query and print the result
foreach ($ query-> execute () as $ row)
{
    foreach ($ row as $ k => $ v)
        print "{$ k}: {$ v} \ n";
}
PDO is officially recommended and a more general database access method. If you have no special needs, then you better learn and use PDO.
But if you need to use the advanced features unique to MySQL, then you may need to try MySQLi, because PDO in order to be able to use on multiple databases at the same time, will not include those MySQL unique features.

MySQLi is an enhanced interface for MySQL, and provides 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, and no examples are given here. You can refer to the PHP official website documentation [Note].

Note: http://www.php.net/manual/en/mysqli.quickstart.php

 

Type constraints

The type of parameters can be restricted through type constraints, but this mechanism is not perfect, and currently only applies to classes and callable (executable types) and array (array), not to string and int.

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

 

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, which can be directly supported by JS. JSON is actually part of JS syntax.

JSON series of functions, you can convert the array structure in PHP and JSON string:

$ array = ["key" => "value", "array" => [1, 2, 3, 4]];
$ json = json_encode ($ array);
echo "{$ json} \ n";

$ object = json_decode ($ json);
print_r ($ object);
Output:

{"key": "value", "array": [1,2,3,4]}
stdClass Object
(
    [key] => value
    [array] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )
)
It is worth noting that json_decode () returns 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, with a lot of new features and some incompatible changes.

 

Deprecated features

The following functions 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), which will register all form variables ($ _GET and $ _POST) as global variables.

See the example below:

if (isAuth ())
    $ authorized = true;
if ($ authorized)
    include ("page.php");
This code sets $ authorized to true when it passes verification. Then it determines whether to display the page based on the value of $ authorized.

But because $ authorized is not initialized to false in advance, when register_globals is turned on, you may access /auth.php?authorized=1 to define the value of this variable and bypass authentication.

This feature is a historical issue and was 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 historical issue and has been removed in PHP5.4.

This feature will escape all user input, which looks good. We mentioned earlier that user input needs to be escaped.

However, PHP does not know which input will enter SQL, which input will enter the shell, and which input will be displayed as HTML, so many times this escaping will cause confusion.

Safe Mode

Many web hosting providers use Safe Mode to isolate multiple users, but Safe Mode has many problems, such as certain extensions do not follow Safe Mode to control permissions.

PHP officially recommends using the operating system mechanism for permission isolation, allowing the web server to run the PHP interpreter with different user permissions.

 

Anonymous function

Also called closures, it is often used to temporarily create an unnamed function for callback functions and so on.

$ func = function ($ arg)
{
    print $ arg;
};

$ func ("Hello World");
The above code defines an anonymous function and assigns it to $ func.

You can see that the function keyword is still used to define anonymous functions, but the function name is omitted, and the parameter list is directly used.

Then we call the anonymous function stored in $ func.

Anonymous functions can also use the use keyword to capture external variables:

function arrayPlus ($ array, $ num)
{
    array_walk ($ array, function (& $ v) use ($ num) {
        $ v + = $ num;
    });
}
The above code defines an arrayPlus () function (this is not an anonymous function), which adds each item in an array ($ array) with a specified number ($ num).

In the implementation of arrayPlus (), we use the array_walk () function, which executes a callback function for each item of an array, which is the anonymous function we defined.

After the parameter list of the anonymous function, we use the use keyword to capture the $ num outside the anonymous function into the function, so as to know how much should be added.

 

Magic method: __invoke (), __callStatic ()

PHP's object-oriented system provides several "magic methods" for implementing "overloading" similar to other languages, such as triggering a magic method when accessing non-existent properties and methods.

With the addition of anonymous functions, PHP introduced a new magic method __invoke ().

This 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 () will be called when a non-existent static method is called.

 

Namespaces

PHP's namespace has a very painful syntax that has no one before and no one after:

<? php
// The separator of the namespace is a backslash, and the statement must be on the first line of the file.
// Any code can be included in the namespace, but only ** classes, functions, constants ** are affected by the namespace.
namespace XXOO \ Test;

// The fully qualified name of this class is \ XXOO \ Test \ A, where the first backslash indicates the global namespace.
class A {}

// You can also define a second namespace in the existing file, the following code will be located in \ Other \ Test2.
namespace Other \ Test2;

// Instantiate objects from other namespaces:
$ a = new \ XXOO \ Test \ A;
class B {}

// You can also define the third namespace with curly braces
namespace Other {
    // Instantiate objects from the sub-namespace:
    $ b = new Test2 \ B;

    // Import names from other namespaces and rename them,
    // Note that only classes can be imported, not functions and constants.
    use \ XXOO \ Test \ A as ClassA
}
For more information about the syntax of namespaces, please refer to the official website [Note].

Note: http://php.net/manual/zh/language.namespaces.php

The namespace is often used 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 will be passed to the autoload function. The autoload function replaces the namespace separator (backslash) in the class name with a slash, and Contains corresponding files.

In this way, hierarchical storage of class definition files can be realized and automatically loaded as needed.

 

Late static binding

PHP's OPP mechanism has inheritance and virtual function-like 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 ();
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:

B :: funcXXOO
It can be seen that when $ this-> funcXXOO () is used in A, it reflects the "virtual function" mechanism, and the actual call is B :: funcXXOO ().

However, if you change all functions 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 is originally "current class", so PHP5.3 gives the static keyword a new feature: late static binding:

class A
{
    static public function callFuncXXOO ()
    {
        print static :: funcXXOO ();
    }

    // ...
}

// ...
This will output as expected:

B :: funcXXOO
 

Heredoc and Nowdoc

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

Heredoc behaves like a double-quoted string:

$ name = "MyName";
echo <<< TEXT
My name is "{$ name}".
TEXT;
Heredoc starts with three left angle brackets, followed by an identifier (TEXT), and ends with an identifier (without indentation) of the same top cell.

Just like double-quoted strings, variables can be embedded in them.

Heredoc can also be used for function parameters and class member initialization:

var_dump (<<< EOD
Hello World
EOD
);

class A
{
    const xx = <<< EOD
Hello World
EOD;

    public $ oo = <<< EOD
Hello World
EOD;
}
Nowdoc behaves like a single quoted string, and you cannot embed variables in it. The only difference from Heredoc is that the identifier after the three left angle brackets must be enclosed in single quotes:

$ name = "MyName";
echo <<< ‘TEXT‘
My name is "{$ name}".
TEXT;
Output:

My name is "{$ name}".
 

Define constants with const

Since PHP5.3, it also supports the use of const to define 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 runtime:

// correct
const XXOO = 1234;
// error
const XXOO = 2 * 617;
 

Ternary operator short form

Old style:

echo $ a? $ a: "No Value";
Can be abbreviated as:

echo $ a?: "No Value";
That is, if the second part of the ternary operator is omitted, the first part will be used instead.

 

Phar

Phar is the PHP Archive, which was only a library in Pear at first. Later, it was rewritten as a C extension in PHP5.3 and built into PHP.

Phar is used to package multiple .php scripts (you can also package other files) into a .phar compressed file (usually in ZIP format).

The purpose is to imitate Java's .jar, wrong, the purpose is to make it easier to publish PHP applications. It also provides functions such as digital signature verification.

The .phar file can be interpreted and executed by the PHP engine like a .php file. At the same time, you can write such code to include (require) the code in .phar:

require ("xxoo.phar");
require ("phar: //xxoo.phar/xo/ox.php");
For more information, please refer to the official website [Note].

Note: http://www.php.net/manual/zh/phar.using.intro.php

 

 

PHP5.4

(2012-2013)

 

Short Open Tag

Short Open Tag has always been available since PHP5.4.

Focus on the issue of PHP start and stop tags here. which is:

<? php
// Code ...
?>
Usually the above form, in addition to a short form:

<? / * Code ... * /?>
You can also put

<? php echo $ xxoo;?>
Abbreviated as:

<? = $ xxoo;?>
This short form is called Short Open Tag, which is enabled by default in PHP5.3 and always available in PHP5.4.

It would be very convenient to use this shorthand to embed PHP variables in HTML.

For pure PHP files (such as class implementation files), PHP officials recommend writing the start tag at the top and omitting the end tag.

This ensures that the entire PHP file is PHP code, and there is no output, otherwise you will encounter some troubles when setting the header and cookie after you include the file [Note].

Note: Header and Cookie must be sent before outputting any content.

 

Array short form

This is a very convenient feature!

// The original array writing method
$ arr = array ("key" => "value", "key2" => "value2");
// Short form
$ arr = ["key" => "value", "key2" => "value2"];
 

Traits

The so-called Traits are "components", a mechanism used to replace inheritance. Multiple inheritance is not possible in PHP, but a class can contain multiple Traits.

// Traits cannot be instantiated separately, only included by the class
trait SayWorld
{
    public function sayHello ()
    {
        echo ‘World!’;
    }
}

class MyHelloWorld
{
    // Include members from SayWorld
    use SayWorld;
}

$ xxoo = new MyHelloWorld ();
// sayHello () function is from SayWorld component
$ xxoo-> sayHello ();
Traits also has many magical functions, such as including multiple Traits, resolving conflicts, modifying access permissions, setting aliases for functions, etc.

Traits can also be included in Traits. Limited space cannot be used for individual examples. For details, please refer to the official website [Note].

Note: http://www.php.net/manual/zh/language.oop5.traits.php

 

Built-in web server

PHP has built a lightweight Web server since 5.4, does not support concurrency, positioning is used for development and debugging environment.

It is indeed very convenient to use it in the development environment.

php -S localhost: 8000
This creates a Web server in the current directory, which you can access through http: // localhost: 8000 /.

Among them, localhost is the listening IP, and 8000 is the listening port, which can be modified by yourself.

In many applications, URL rewriting is performed, so PHP provides a function to set the routing script:

php -S localhost: 8000 index.php
In this way, all requests will be handled by index.php.

You can also use XDebug for breakpoint debugging.

 

Details modification

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

$ func = "funcX
XOO ";
A :: {$ func} ();
Added features to access class members during instantiation:

(new MyClass)-> xxoo ();
Added support for parsing access to members of the array returned by the function (this writing method will report errors in previous versions):

print func () [0];
 

 

PHP5.5

(Since 2013)

 

yield

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

function number10 ()
{
    for ($ i = 1; $ i <= 10; $ i + = 1)
        yield $ i;
}
The return value of this function is an array:

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

list () for foreach

You can use list () to parse nested arrays in foreach:

$ array = [
    [1, 2, 3],
    [4, 5, 6],
];

foreach ($ array as list ($ a, $ b, $ c))
    echo "{$ a} {$ b} {$ c} \ n";
result:

1 2 3
4 5 6
 

Details modification

The mysql function is not recommended, PDO or MySQLi is recommended, see above.

Windows XP is no longer supported.

Use MyClass :: class to get the fully qualified name of a class (including the namespace).

empty () supports expressions as parameters.

A finally block is added to the try-catch structure.

 

 

PHP5.6

 

Better constant

When defining constants, calculations using previously defined constants are allowed:

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 in place of func_get_args ()

function add (... $ args)
{
    $ result = 0;
    foreach ($ args as $ arg)
        $ result + = $ arg;
    return $ result;
}
At the same time, when calling the function, the array can be expanded into function parameters:

$ arr = [2, 3];
add (1, ... $ arr);
// the result is 6
 

Namespaces

The namespace supports constants and functions:

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

 

reference:

http://segmentfault.com/blog/jysperm/1190000000403307

[The history of PHP development] Detailed explanation of the new functions in PHP5.2 to PHP5.6

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: info-contact@alibabacloud.com 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.