Home Backend Development PHP Tutorial Important new features of PHP 5.4 official version

Important new features of PHP 5.4 official version

Nov 23, 2016 pm 01:26 PM

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles