Home  >  Article  >  Backend Development  >  Important new features of PHP 5.4 official version

Important new features of PHP 5.4 official version

巴扎黑
巴扎黑Original
2016-11-23 13:26:451130browse

PHP has always been a very important and fast and convenient development language in the field of web development, and is favored by the majority of developers. Now the official version of PHP 5.4 has been released, which adds a lot of new features. The official claims that the performance is improved by 20% and takes up less resources. In this article, I will lead you to learn some new features of PHP 5.4.

 In PHP 5.4, first of all, more than 100 bugs have been fixed, and memory and performance optimization have been done better, and some methods of previous versions have been removed, such as register_globals, magic_quotes, safe_mode, etc., and It should be noted that in PHP 5.4, the default encoding method has been changed to UTF-8, which is very helpful for developers to develop multi-language applications.

  Introduction to Traits

First, let’s introduce the new feature Traits added in PHP 5.4. In fact, this function can also be seen in other languages. It can be simply understood as a collection of methods. The organizational structure is somewhat similar to a class (but it cannot be instantiated like a class), allowing developers to use different methods. Reuse this set of methods in the class. Since PHP is a single-inheritance language, one class cannot inherit multiple classes at the same time. At this time, Traits come in handy.

 Traits is a collection of solutions that does not belong to any actual class. Users cannot create Trait instances or directly call methods in Traits. Instead, users must merge Traits into actual classes to use them. In terms of priority, the Trait method will override the inherited method of the same name, and the method of the same name in the current merged class will override the Trait method.

 The following is an example to illustrate the use of Traits. Suppose that the website we are building needs to call the APIs of Facebook and Twitter at the same time. During the calling process of these two APIs, we need to call the curl method to perform a series of operations to obtain the content returned by the two API interfaces. In order not to Repeatedly writing the same method in these two classes can be implemented using Traits 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;

}



 public function get ($url)

 {

  return json_decode($this->curl('http://api.twitter.com/'.$url));

  }

 }

  /**Twitter API classes*/

 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('500058753')->name; //Here it will be Call the API to output the Facebook username

 /**Facebook API classes*/

 echo (new Facebook_API)->get('500058753')->name;

 $foo = 'get';

echo (new Facebook_API)->$foo('500058753')->name;

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



In the above code, a function set is first defined through the keyword trait. Its name is Curl, which contains a method named curl. In this method, the built-in cur in PHP is called based on the parameter value of the url. The method returns the page output content corresponding to the url. Then in the Twitter_API class and Facebook_API class, use cURL is used to call the Traits respectively, and in their respective get methods, the curl method in Traits is called.

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

  Class members can be accessed during instantiation, that is:

echo (new Facebook_API)->get('500058753')->name;

 $foo = 'get';

 echo (new Facebook_API)->$foo('500058753')-> name;




Did you see it? The $foo variable is assigned the value get, and then when trying to call the get method in the class, it is through (new Facebook_API)->$foo('500058753')->name ; to implement the call.

Let's give another example to illustrate the use of Traits. This example may be simpler, such as the following code:

Trait Net

 {

 public function net()

 {

  return 'Net';

 }

  }

  Trait Tuts

 {

  public function tuts()

 {

  return 'Tuts'; ts

 {

 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 The results are all output to NetTuts. Also, by the way, the magic constant for traits in PHP 5.4 is __TRAIT__.

 Built-in debugging server

  In the past PHP development, it generally needed to be developed in conjunction with Apache HTTP Server. In PHP 5.4, a simple web server is built-in to facilitate developers to complete development work without complicated configuration. The following is a step-by-step explanation of how to use the built-in server in PHP 5.4 to complete relevant work in a Windows environment.

 Step 1) First create a directory in 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
}
?>





  Then 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:

include_path = ".;C:phpPEAR;C:public_html"



Step 2 Run the built-in web server

First enter 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
 It specifies that any machine can access this server, and specifies port 8080, and specifies that the routing file for work monitoring is the router and php files under c:public_html. After entering the above command line and pressing Enter, the following message prompt will appear

, which proves that the built-in server has been started correctly.

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

 More concise array syntax

In PHP 5.4, some syntax support is more concise, such as declarations in arrays. Now

 supports the use of brackets to declare, as follows:

$fruits = array ('apples', 'oranges', 'bananas'); // Old declaration method

  $fruits = ['apples', 'oranges', 'bananas']; // New declaration method supported in PHP 5.4

   // New associative array access

  $array = [

  'foo' => 'bar',

  'bar' => 'foo'

  ];




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

  Directly access array values ​​from function return values ​​

  In PHP 5.4, it is supported to directly access array values ​​from function return values. Take an example, for example:

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

 echo $tmp[1]; // Mathison

 In this example, if it is before PHP 5.4, it needs to be taken out For Mathison in the string above, 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 access the return value from an array, as follows:

echo explode(' ', 'Alan Mathison Turing')[1];
 This is much more convenient. For another example, to add Turing, the last string part of the above string, you can do this in PHP 5.4:

echo end(explode(' ', 'Alan Mathison Turing'));
  Then give a complex Examples of points are as follows:

function foobar()

 {

  return ['foo' => ['bar' => 'Hello']];

 }

 echo foobar()['foo']['bar']; //Output Hello




The $this pointer can be used in closures

In previous PHP versions, it was not possible to use the $this pointer in anonymous methods (also called closures), but in PHP 5.4 it is possible The example is as follows:

class Foo

 {

  function hello() {

  echo 'Hello Nettuts!';

 }

  function anonymous()

  {

 () {

 $ this->hello(); //This was not possible in previous versions.

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

  $x(); // What is executed is Foo::hello()

 }

 }

  new Bar(new Foo); //Output Hello Nettuts!

 The above implementation method is a bit complicated. In PHP 5.4, it can be more conveniently written as follows:

 function anonymous()

 {

  $that = $this;

  return function() use ($that) {

  $that->hello();

  }; How to mark Settings can be used in templates at any time to replace this method. Use the "0b" prefix to identify binary numbers. Now, if you want to use binary numbers, please add the 0b prefix in front, such as:

  Echo 0b11111

Enhancement of function type hints

Since PHP is a weakly typed language, so After PHP 5.0, the function type hint function was introduced, which means that all parameters in the incoming function are type checked. For example, there is the following class:

 class bar {

 }

 function foo( bar $foo) {

 }

  The parameters in function foo stipulate that the parameters passed in must be instances of the bar class, otherwise the system will make a judgment error. Similarly for arrays, judgment can also be made, for example:

 function foo(array $foo) {

  }

 foo(array(1, 2, 3)); // Correct, because the array is passed in

  foo(123); // Incorrect, the passed in 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, we would need to do a lot of extra work to check whether it is the correct callback function that is callable. The example is as follows:

 function foo(callable $callback) {

  }

  Rules:



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

 foo("printf"); //Correct

 foo(function(){}); //Correct

 class A {

 static function show() {

  }

 }

 foo(array("A", "show")); //Correct



 Unfortunately, in PHP 5.4, Type hints for basic types such as characters, integers, etc. are still not supported.

  Enhancement of time statistics

  In PHP 5.4, $_SERVER['REQUEST_TIME_FLOAT'] is newly added, which is used to count service request time and is expressed in ms, which greatly facilitates developers, such as:

  echo 'script execution time', round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 2), 's';

  Summary:

 This article briefly summarizes some new features in PHP 5.4, you can We can see that the more obvious feature improvements in PHP 5.4 are mainly Traits and built-in debugging server, UTF-8 default support, etc. For detailed introduction of new features, please refer to the user manual of PHP 5.4.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn