Important new features of PHP5.4 official edition

Source: Internet
Author: User
Tags traits
Now the official version of PHP5.4 has been released, with a large number of new features added. The official website claims that the performance is improved by 20%, and it consumes less resources. In this article, I will lead you to learn some new features of php5.4. PH .. PHP has always been an important and convenient development language in the Web development field, and is favored by developers. Now the official version of PHP 5.4 has been released, adding a large number of new features. the official website claims that the performance is improved by 20%, and it consumes less resources. In this article, I will lead you to learn some new features of PHP 5.4.

In PHP 5.4, the first issue is to fix as many as 100 bugs, improve the memory and performance optimization, and remove some earlier versions of methods, such as register_globals, magic_quotes, safe_mode and so on, and note that in PHP 5.4, the default encoding method has changed to UTF-8, which is very helpful for developers to develop multi-language version applications.

Traits introduction

First, we will introduce the newly added Traits in PHP 5.4. In fact, this function is also available in other languages. it can be simply understood as a collection of methods, and it is similar to the class in the organizational structure (but cannot be instantiated like the class ), developers can reuse this method in different classes. Because php is a single-inherited language, a class cannot inherit multiple classes at the same time. At this time, Traits will be used.

Traits is a set of solutions and does not belong to any actual class. You cannot create a Trait instance or directly call methods in Trait. Instead, you must merge Traits into the actual class to use them. In terms of priority, the Trait method will overwrite the inherited methods of the same name, while the methods of the same name in the current merge class will overwrite the Trait method.

The following example describes the usage of Traits. Assume that the APIs of Facebook and Twitter need to be called at the same time in the website we are building. during the call of these two APIs, the curl method must be called for a series of operations, obtain the content returned by the two API interfaces. to not write the same method repeatedly 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/'.w.url ));

}

}

/** Facebook API class */

Class Facebook_API

{

Use cURL; // call Traits

Public function get ($ url)

{

Return json_decode ($ this-> curl ('http: // graph.facebook.com/'.w.url ));

}

}

$ Facebook = new Facebook_API ();

Echo $ facebook-> get ('20140901')-> name; // The API is called to output the facebook user name.

/** Demonstrate new features in php 5.4 */

Echo (new Facebook_API)-> get ('20140901')-> name;

$ Foo = 'get ';

Echo (new Facebook_API)-> $ foo ('20140901')-> name;

Echo (new Twitter_API)-> get ('1/users/show. json? Screen_name = rasmus ')-> name;



In the above code, a feature set is defined by the keyword trait, and its name is Curl, which contains a method named curl, which is based on the url parameter value, call the php built-in cur method to return the page output content corresponding to the url. Then in the Twitter_API class and Facebook_API

Class, respectively use cURL to call this Traits, and in each get method, call the curl method in Traits.

Note: In the above code, apart from using new Facebook_API () to generate facebook objects, we also demonstrated the new features in php 5.4, namely:

It can be a member of the sequence class during instantiation, namely:

Echo (new Facebook_API)-> get ('20140901')-> name;

$ Foo = 'get ';

Echo (new Facebook_API)-> $ foo ('20140901')-> name;




Have you seen it? Assign a value to the $ foo variable to get, and then call the get method in the enterprise diagram of the class through (new Facebook_API)-> $ foo ('20140901')-> name; to implement the call.

Let's take another example to illustrate the use of Traits. this example may be simpler, for example, 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 ();




All the above results output NetTuts. In php 5.4, the magic constant of traits is _ TRAIT __.

Built-in debugging server

In the past, php development usually requires cooperation with Apache HTTP Server. In php 5.4, a simple Web server is built in to help developers complete development without complex configurations. The following describes how to use the built-in server in php 5.4 in a windows environment.

Step 1) first create a directory under the root directory of the c drive, which is public_html, and create a router. php file in the file. the code is as follows:

// 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
}
?>





Create a simple php file named index. php, as follows:

// Index. php

Echo 'hello Nettuts + Readers! ';

?>

Then open the installation directory of php 5.4, find php. ini, and add the following line to include_path:

Export de_path = ".; C: \ php \ PEAR; C: \ public_html"



Step 2 run the built-in web server

First, run 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
In this example, any machine can access this server, port 8080 is specified, and the routing file for the job listening is the router and PHP files under c: \ public_html, enter the command line above and press Enter. the following message is displayed:

It indicates that the built-in server has been correctly started.

At this time, you can enter http: // localhost: 8080/index. php in the browser to access the website.

More concise array syntax

In php 5.4, the support for some syntaxes is more concise, such as declarations in arrays.

Brackets can be used to declare the statement as follows:

$ Fruits = array ('append', 'oranges', 'bananas'); // The old Declaration method

$ Fruits = ['apples ', 'oranges', 'bananas']; // The supported declaration method in php 5.4

// New connected array access

$ Array = [

'Foo' => 'bar ',

'Bar' => 'foo'

];




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

Returns an array of function values.

In php 5.4, you can directly set an array value for function return values. Let's look at an example, for example:

$ Tmp = explode ('', 'Alan Mathison Turing ');

Echo $ tmp [1]; // Mathison

In this example, if you want to retrieve Mathison from the above string before php 5.4, you must first use the explode function to return the relevant value and then take the value of the array. In php 5.4, you can directly set values for the returned values as follows:

Echo explode ('', 'Alan Mathison Turing ') [1];
This makes it much easier. For example, if you want to obtain the Turing of the last string of the above string, you can do this in php 5.4:

Echo end (explode ('', 'Alan Mathison Turing '));
The following is an example of a complex point:

Function foobar ()

{

Return ['foo' => ['bar' => 'hello'];

}

Echo foobar () ['foo'] ['bar']; // output Hello




$ This pointer can be used in closures

In previous php versions, the $ this pointer cannot be used in anonymous methods (also called closures), but in php 5.4, the $ this pointer can be used. The example is as follows:

Class Foo

{

Function hello (){

Echo 'hello Nettuts! ';

}

Function anonymous ()

{

Return function (){

$ This-> hello (); // this cannot be implemented in previous versions

};

}

}

Class Bar

{

Function _ construct (Foo $ o)

{

$ X = $ o-> anonymous (); // actually calls Foo: hello ()

$ X (); // The execution is Foo: hello ()

}

}

New Bar (new Foo); // output Hello Nettuts!

The above implementation method is a bit complex. in php 5.4, it is easier to write as follows:

Function anonymous ()

{

$ That = $ this;

Return function () use ($ that ){

$ That-> hello ();

};

}




 



Now, regardless of how to set the short_tag tag in php. ini, you can use this method in the template at any time, instead of this method. Use the "0b" prefix to identify the binary number. now, if you want to use the binary number, add the 0b prefix to the front, for example:

Echo 0b11111

Enhancement of function type prompts

Because php is a weak language, after php 5.0, the function type prompt function is introduced, which means that all parameters in the input function are checked for the type. for example, there are the following classes:

Class bar {

}

Function foo (bar $ foo ){

}

The parameter in function foo specifies that the input parameter must be an instance of the bar class. Otherwise, the system determines that an error occurs. You can also judge the array, for example:

Function foo (array $ foo ){

}

Foo (array (1, 2, 3); // correct, because the input is an array

Foo (123); // incorrect. the input is not an array.




In php 5.4, the callable type is supported. In the past, if we wanted a function to accept a callback function as a parameter, we had to do a lot of extra work to check whether it was callable and correct. The example is as follows:

Function foo (callable $ callback ){

}

Then:



Foo ("false"); // error, because false is not of the callable type

Foo ("printf"); // correct

Foo (function () {}); // correct

Class {

Static function show (){

}

}

Foo (array ("A", "show"); // correct



Unfortunately, in PHP 5.4, the type prompts for basic types such as characters and shaping are still not supported.

Time statistics enhancement

In PHP 5.4, $ _ SERVER ['request _ TIME_FLOAT '] is added, which is used to count the service REQUEST time and expressed in ms, which greatly facilitates developers, for example:

Echo 'script execution time', round (microtime (true)-$ _ SERVER ['request _ TIME_FLOAT '], 2), 'S ';

Summary:

This article briefly summarizes some new features of PHP 5.4, we can see that PHP 5.4 is more obvious feature improvement mainly Traits and built-in debugging server, UTF-8 default support, etc, for more information about the new features, see 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.