PHP 5.4 Official edition important new features

Source: Internet
Author: User
Tags anonymous execution explode net new features php file string traits

PHP has been in the field of web development is very important and fast and convenient development of language, by the vast number of developers of all ages. Now that the official version of PHP 5.4 has been released, which has added a lot of new features, officials say that performance is up 20% and that it takes less resources. In this article, I'm going to take you through some of the new features of PHP 5.4.

In PHP 5.4, the first is to fix up to 100 bugs, and do better on memory and performance optimizations, and remove some previous versions of the methods, such as Register_globals,magic_quotes,safe_mode, and note that In PHP 5.4, the default encoding has been changed in order to help developers develop multilingual versions of the application.

Traits Introduction

First, introduce the new feature traits in PHP 5.4. In fact, this feature is also seen in other languages, it can be simply understood as a set of methods, in the organizational structure with the class (but not as instantiated), so that developers can reuse this set of methods in different classes. Because PHP is a single inherited language, it is not possible to inherit multiple classes at the same time in a class. At this time, traits came in handy.

Traits is a collection of scenarios that does not belong to any actual class. Instead of creating trait instances or directly calling methods in trait, users must merge traits into the actual class to use them. On the priority side, the trait method overrides the inherited method of the same name, and the method of the same name in the current merge class overrides the Trait method.

Here is an example to illustrate the use of traits. Suppose we're building a Web site that calls for both Facebook and Twitter APIs, and in these two API calls, we need to invoke the curl method to do a series of operations to get the content returned by both API interfaces, in order not to repeat the same method in these two classes. You can use the traits implementation in PHP 5.4, as shown in the following code:

/** CURL Wrapper Trait * *

Trait CURL

Public Function Curl ($url)

$ch = Curl_init ();

curl_setopt ($ch, Curlopt_url, $url);

curl_setopt ($ch, Curlopt_returntransfer, 1);

$output = curl_exec ($ch);

Curl_close ($ch);

return $output;

/** Twitter API Class * *

Class Twitter_api

Use CURL; Call traits

Public function Get ($url)

Return Json_decode ($this->curl ("http://api.twitter.com/". $url));

/** Facebook API Class * *

Class Facebook_api

Use CURL; Call traits

Public function Get ($url)

Return Json_decode ($this->curl ("http://graph.facebook.com/". $url));

$facebook = new Facebook_api ();

echo $facebook->get ("name; This will invoke the API to output the user name of the Facebook

/** demonstrates the new features in PHP 5.4 * *

Echo (New Facebook_api)->get ("name;

$foo = "Get";

Echo (new Facebook_api)-> $foo ("name;

Echo (New Twitter_api)->get ("name;

In the above code, first through the keyword trait defines a feature set, its name is curl, which contains a method named Curl, which is based on the parameter value of the URL, call the PHP built-in Cur method to return the URL corresponding to the page output. And then in the Twitter_api class and Facebook_api

Class, the traits is invoked using the use curl, and in the respective get methods, the Curl method in traits is invoked.

Note that in the above code, in addition to using new Facebook_api () to generate an instance of the Facebook object, we also demonstrated the use of the new features in PHP 5.4, namely:

Class members can be accessed at instantiation time, that is:

Echo (New Facebook_api)->get ("name;

$foo = "Get";

Echo (new Facebook_api)-> $foo ("name;

You see that? The $foo variable is assigned to get, and when an attempt to call a Get method in a class is made, it is implemented by the (new Facebook_api)-> $foo ("500058753")->name;.

Let's take another example to illustrate the use of traits, which may be simpler, such as the following code:

Trait Net

Public Function Net ()

return "Net";

Trait Tuts

Public Function tuts ()

return "Tuts";

Class NetTuts

Use Net, tuts;

Public Function Plus ()

return "+";

$o = new NetTuts;

echo $o->net (), $o->tuts (), $o->plus ();

Echo (New NetTuts)->net (), (new NetTuts)->tuts (), (new NetTuts)->plus ();

The above results are output nettuts. In addition, by the way, the traits magic constant in PHP 5.4 is __trait__.

built in Debug server

In the previous development of PHP, it is generally necessary to develop with the Apache HTTP server. In PHP 5.4, a new built-in Web server is built to make it easier for developers to do development work without having to use complex configurations. Below is a step-by-step tutorial on how to use the built-in server in PHP 5.4 to do the work in a Windows environment.

Step 1 First in the C-packing directory to create a directory, for Public_html, and in the file to create a router.php file, the code is as follows:

Php

router.php

if (Preg_match ("#\.php$#", $_server["Request_uri"))

Require basename ($_server["Request_uri")); Serve PHP file

else if (Strpos ($_server["Request_uri"], ".")!== false)

return false; Serve file As-is

>

Then create a simple php file, named index.php, as follows:

index.php

echo "Hello nettuts+ readers!";

>

Then open the PHP 5.4 installation directory, find PHP.ini, and then add the following line to the Include_path:

include_path = ".; C:\php\PEAR; C:\public_html "

Step 2 Run the built-in Web server

First proceed to the command line mode, and enter the PHP directory, enter the following command:

Php-s 0.0.0.0:8080-t C:\public_html router.php

Where you specify that any machine can access this server, and specify the 8080 port, the job listener specified the route file for the c:\public_html under the router,php file, in the above command line input and press ENTER, the following message will appear

It proves that the built-in server has started correctly.

This time, you can enter http://localhost:8080/index.php in the browser for access.

More Concise array syntax

In PHP 5.4, some of the syntax support is more concise, such as the declaration in the array, now

Supports the use of the Bracket method to declare the following:

$fruits = Array ("Apples", "oranges", "Bananas"); Old way of declaring

$fruits = ["Apples", "oranges", "Bananas"]; New support Declaration mode in PHP 5.4

New Associative array access

$array = [

"foo" => "Bar",

"Bar" => "foo"

];

Of course, in PHP 5.4, the old array declaration method is also supported.

array value directly on function return value

In PHP 5.4, the array value of the function return value is supported directly. Look at an example, for example:

$tmp = Explode ("", "Alan Mathison Turing");

echo $tmp [1]; Mathison

In this example, if you want to remove the Mathison from the above string before PHP 5.4, you must first return the relevant value using the EXPLODE function, and then take the values of the array. In PHP 5.4, the return value can be evaluated directly by an array of values, as follows:

echo Explode ("", "Alan Mathison Turing") [1];

This is much more convenient. Add, for example, to get the last string part of the string Turing, which you can do in PHP 5.4:

Echo End (Explode ("", "Alan Mathison Turing"));

Another example of a complex point is the following:

function Foobar ()

return ["foo" => ["Bar" => "Hello"]];

Echo Foobar () ["foo"] ["bar"]; Output Hello

$this pointers can be used in closures

In previous versions of PHP, it was not possible to use the $this pointer in anonymous methods (also known as closures), and PHP 5.4 was OK, as the following examples are:

Class Foo

function Hello () {

echo "Hello nettuts!";

function Anonymous ()

return function () {

$this->hello (); This is not possible in previous releases

};

Class Bar

function __construct (Foo $o)

$x = $o->anonymous (); Actually call Foo::hello ()

$x (); The execution is Foo::hello ()

New Bar (new Foo); Output Hello nettuts!

The above implementation is a bit more complicated, in PHP 5.4, it can be more easily written as follows:

function Anonymous ()

$that = $this;

return function () use ($that) {

$that->hello ();

};

Now, regardless of how the Short_tag tag in php.ini is set, you can use this in a template to replace the way it is. Using the prefix "0b" to identify the binary number, now, if you want to use the binary number, precede the prefix with 0b, for example:

Echo 0b11111

enhancement of function type hints

Since PHP is a weakly typed language, after PHP 5.0, the function type hint is introduced, meaning that the type check for parameters in the incoming function, for example, is the following class:

Class Bar {

function foo (bar $foo) {

The parameters in the function foo specify that the incoming arguments must be instances of the bar class, or the system will judge an error. Also, for arrays, you can make judgments, such as:

function foo (array $foo) {

Foo (Array (1, 2, 3)); Correct, because the array is passed in

Foo (123); Incorrect, incoming is not an array

In PHP 5.4, support for callable types is supported. In the past, if we wanted a function to accept a callback function as a parameter, it would take a lot of extra work to check if it was a callable, correct callback function, as in the following example:

function foo (callable $callback) {

The

Foo ("false"); Error because false is not a callable type

Foo ("printf"); That's right

Foo (function () {}); That's right

Class A {

static function Show () {

Foo (Array ("A", "show")); That's right

Unfortunately, PHP 5.4 still does not support type hints for basic types such as characters, shaping, and so on.

The enhancement of Time statistics

In PHP 5.4, the new addition of $_server["Request_time_float", which is used to statistical service request time, and MS to express, greatly facilitate the developer, such as:

echo "Script execution Time", round (Microtime (true)-$_server["Request_time_float"], 2), "s";

Summary:

This article briefly summarizes some of the new features in PHP 5.4, you can see that the more obvious features of PHP 5.4 improvement is traits and built-in debugging server, default support, etc., detailed new features, please refer to the PHP 5.4 user manual



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.