PHP5.4 Latest Features

Source: Internet
Author: User
Tags apc deprecated new set parse error rfc small web server drupal zend framework
PHP5.4 Latest Features

Official website: changelog-5.php#5.4.0

Oracle: TheLAMP system has a new competition, but the features in this release make PHP challenging the limit again. made a slight change. :

Overview Summary:
1. Memory and performance improvements: 20-50% memory is saved in large PHP applications. Improved performance through various optimizations 10-30%
2. Support Features trait
3. Thin array syntax, you can define a short array
4. Function array dereference, support array dereferencing,
5. Instance method invocation
6. Closure Bindings
7. Object is function
8. Built-in Web server (CLI)
9. Native session Handler Interface
Jsonserializable interface
11. Binary notation
12. Improved error messages
13. Array-to-string conversion notification
14. Enhancement of function type hints (callable Typehint)
15. Enhanced time statistics, high-precision timers
16. Upload progress bar Upload progress
Zend Signal in PHP 5.4
PHP 5.4 introduced a three-dimensional optimization scheme by Arnaud.

1) Deprecated: Allow_call_time_pass_reference, Define_syslog_variables, highlight.bg, Register_globals, register_long_arrays , Magic_quotes, Safe_mode, Zend.ze1_compatibility_mode, Session.bug_compat42, Session.bug_compat_warn and Y2k_ Compliance
2) no longer supports break and continue in PHP with variable syntax
3) Mysqlnd This bundled MySQL native driver library is now used by default for various extensions that communicate with MySQL, unless the./configure is explicitly overwritten at compile-time.


About eight years ago, I wrote an article called "Do You know PHP?" for the Oracle technology network. "The article. In that article, I talked about PHP's stubborn functionality over forms of "Web problem" solutions, and the ability it has to make things easier. At the time, we were about to release PHP 5.0. Now, nearly 10 years later, we launched the new PHP 5.4.0 version, although a lot of things happened during this period, but there are many things have not changed at all.

One thing that hasn't changed is that ecosystems are as important as ever. Solving Web problems is not just about scripting language choices, it's about the entire ecosystem around you. Now that the LAMP system has prevailed for nearly 15 years, it is still popular, but we are beginning to notice other powerful solutions. The PHP-FPM with Nginx has quickly become popular, since PHP 5.3 has greatly improved support and has been further simplified in 5.4. The M (i.e. database) part of the system also began to become very different from the 8 years ago. A variety of NoSQL solutions and MySQL Cluster offer a richer set of choices than just putting everything in the MyISAM table.

A variety of interesting technologies have emerged, so we have written PHP extensions to easily access these technologies. One of my favorite extensions is libevent, which can be used to write event-driven high-performance applications in PHP. The other is ZeroMQ, which is a premium socket font. Much like SQLite no longer needs to write another original file format and associated parser, ZeroMQ also does not need to use socket protocols and associated socket processing code for any reason. You can even combine libevent and ZeroMQ to get independent, high-performance, event-driven, superior servers. (If you are interested in this, see this example.) I also like SVM (Support vector machine) This machine learning algorithm, you do not have to be a fan of machine learning can also ask a lot of questions.

There are many extensions that have been widely accepted in recent years. In particular, Gearman became popular, becoming part of a common system of user deployment. You can dispatch jobs through Gearman so that the jobs are completed asynchronously by the worker. The worker can be spread across multiple servers, and they can even further dispatch more MapReduce type jobs.

After PHP 5.0 was released in 2004, the next 5.1 was introduced in 2005, which added DateTime implementations, PDO, and performance improvements. PHP 5.2 was released in 2006, introducing an improved memory manager, JSON support, and input filtering. At the time, we started pushing PHP 6, an extremely ambitious plan to completely rewrite everything about the ICU (Unicode internationalized components) library. It turns out that the plan was a little too hasty-we couldn't get enough developers excited, and eventually we had to add the various features that were going to introduce PHP 6 to PHP 5.3, which was released in 2009. The 5.2 and 5.3 lapse of 3 years, which also means that 5.3 has added a lot of content to PHP: namespaces, late static bindings, closures, garbage collection, restricted Goto, MYSQLND (MySQL native driver), better Windows performance, and many other content.

In hindsight, it might make sense to refer to this version as PHP 6, but PHP 6 is equivalent to the efforts made in Unicode to write books about it, so we think we can't publish PHP 6 without significant improvements to Unicode. We introduced the ICU extension called "Intl", which is also compiled for PHP 5.2, which gives you access to more ICU functionality. The mbstring extension continues to evolve over time, which means that almost any Unicode-related problem has a solution, but not explicitly integrated into the language itself.

This introduced PHP 5.4 in 2012. And, for nearly 3 years from the previous version, we have improved some of this during this period. I prefer to revert to a release every year, with fewer new features in each version.

Here are the key features you'll see when you upgrade to 5.4:

1. Memory and performance improvements

Many internal structures have become smaller or disappear altogether, saving 20-50% of memory in large PHP applications. Performance is improved by a variety of optimizations 10-30% (primarily depending on what the code does), including inline common code paths, adding $GLOBALS to the JIT, "@" operator operations faster, adding runtime classes/functions/constant caches, runtime string constants being detained now, Faster access to constants through pre-computed hashing, empty arrays faster and faster processing with less memory, unserialize () and FastCGI requests, and more memory and performance tuning throughout the code.

For example, earlier tests showed that the Zend Framework increased by 21% in 5.4 and memory usage by 23%, while Drupal memory usage decreased by 50% and ran about 7% faster.

2. Support Features trait

Trait is probably the most talked-about feature in PHP 5.4-as a compiler-assisted copy-and-paste. Trait is also a feature of Scala. Other languages may refer to them as "mixin"-or they are not named at all, but have an extensible interface mechanism that allows the interface to contain the actual implementation of its methods.

In contrast to mixin, trait in PHP includes explicit conflict resolution mechanisms for situations where multiple trait implement the same method.

Trait Singleton {public    static function getinstance () {...}} Class A {use    Singleton;    // ...} Class B extends Arrayobject {use    Singleton;    

See php.net/traits for more examples, including conflict resolution syntax, method prioritization, visibility, and support for constants and attributes in trait. In addition, to learn more about conceptual theory, you can read Nathan Sch?rli's paper "Trait: Combinatorial classes in behavior building blocks".

3. Thin array syntax

A new simple but very popular syntax:


That is, you now no longer need to use the "array" keyword to define an array.

4. Function array dereference, support array dereferencing,

1) Another common syntax added. function calls that return an array can now be dereferenced directly:

function fruits () {    return [' Apple ', ' banana ', ' orange '];} echo Fruits () [0]; Outputs:apple


2) with the array dereferencing, the previous notation is no longer necessary:


List ($name,) = Explode (",", "laruence, male");
?>
Instead, the following is:
$name = Explode (",", "B, X") [0];
In addition, Array derefencing can also appear in the lvalue of the re-assignment statement, that is, theoretically you can write:
Explode (",", "Test1, Test2") [3] = "Phper";

5. Instance method invocation

Related to dereferencing an array of functions, you can now invoke an object instantiation method. As with earlier versions, of course you can still link method calls, so you can now write the following code:

class Foo {public    $x = 1;     Public Function GetX () {        return $this->x;    }    Public Function SetX ($val) {        $this->x = $val;        return $this;    

However, because the instantiated object may be discarded, you should instead use a static method call here unless your constructor performs a useful operation. If you use it in conjunction with thin array syntax and function array dereference, we can write some very complex code:

Class Foo extends Arrayobject {public    function __construct ($arr) {        parent::__construct ($arr);    

After a glance, can you tell what the output is? Here, we pass the two-dimensional array to the constructor that returns only the array. Then we select the first element of the second dimension, so this will output "4".

6. Closure Bindings

Referencing an anonymous function (also called a closure function) through $this in a class instance

Closures were introduced in PHP 5.3, but in 5.4 we improved the way closures interact with objects. For example:

Class Foo {  private $prop;  function __construct ($prop) {    $this->prop = $prop;  }  Public Function GetPrinter () {    return function () {echo ucfirst ($this->prop);};  

Note that the closure access $this->prop this private property. By default, closures in PHP use pre-binding-this means that variables within closures have values that define closures. You can use a reference to convert it to a post-binding. However, you can also rebind closures:


Here, we rebind the closure from the $a instance to the instance in the $b. If you do not want closures to access object instances at any time, you can declare closures as static:

Class Foo {  private $prop;  function __construct ($prop) {    $this->prop = $prop;  }  Public Function GetPrinter () {    return static function () {echo ucfirst ($this->prop);}}  $a = new Foo (' Bar ');; $func = $a->getprinter (); $func (); Fatal error:using $this When not in object context

7. Object is function

There is a new magical method called "__invoke", which uses the following:

Class Moneyobject {    private $value;    function __construct ($val) {        $this->value = $val;    }    function __invoke () {        return sprintf (' $%.2f ', $this->value);}    } $Money = new Moneyobject (11.02/5*13); echo $Money (); Outputs: $28.65

8. Built-in Web server (CLI)

The CLI server is a small Web server implementation that can be run from the command line:

% php-s localhost:8000php 5.4.0 Development Server started at Sun Mar one 13:27:09 2012Listening on localhost:8080document Root is/home/rasmuspress ctrl-c to quit.


The CLI server is not intended to be used as a production WEB server; We will use it to run some PHP regression tests, other unit testing mechanisms can use it, and the IDE may use it. It does have some very useful features for routine code debugging from the command line. By default, it uses the current directory as a documentroot, and it also handles static file requests. The default directory index file is "index.php", so you can activate it in a directory full of. PHP,. css,. jpg, and so on. For more complex applications that may use Mod_rewrite to send all requests to a front-end controller or router, you can wrap this router together with a simple small script and start the CLI server as follows:

% php-s localhost:8080/path/to/router.phpphp 5.4.0 Development Server started at Sun Mar one 13:28:01 2012Listening on lo Calhost:8080document Root is/tmp/webpress ctrl-c to quit.


The router.php script might resemble the following:

 

This wrapper loads directly. PHP requests, which will contain "." Any other request is passed to the static file handler, and all other content is passed to the framework's router. You can run Drupal and Symphony directly from the command line.

9. Native session Handler Interface

This is a small and convenient feature that can now be used to implement the session handler interface. You can now pass an instance of a session-processing object to Session_set_save_handler () only, without having to pass it to six more troublesome functions:

Sessionhandler implements Sessionhandlerinterface {public  int close (void) public  int Destroy (string $session ID) Public  int GC (int. $maxlifetime) Public  int Open (String $save _path, string $sessionid) public  Strin G Read (String $sessionid)  


Jsonserializable interface

You can now control what happens when someone tries to encode your object using Json_encode () by implementing the Jsonserializable interface:

Class Foo implements jsonserializable {    private $data = ' Bar ';    Public Function jsonserialize () {        return array (' data ' = = $this->data);}    } Echo Json_encode (new Foo); Outputs: {"Data": "Bar"}

11. Binary notation

To align with native 16 and octal support for PHP, binary notation is now supported: binary numbers are identified with the "0b" prefix

$mask = 0b010101;

12. Improved error messages

The error message is slightly improved.

Before improvement:

% Php-r ' class ABC foo ' Parse error:syntax error, unexpected t_string, expecting ' {' Command line code on line 1


After improvement:

% Php-r ' class ABC foo ' Parse error:syntax error, unexpected ' foo ' (t_string), expecting ' {' Command line code on line


The improvement may not be obvious, but the difference is that the value of the offset tag "foo" is now displayed in the error message.

13. Array-to-string conversion notification

If you are using PHP all the time, you might end up programming with the word "array" appearing randomly in the page, because you try to output the array directly. Whenever an array is converted directly to a string, there is a good chance that an error will occur, and now there is a notification for that situation:


Note : array-to-string conversions in example.php onlline 2



enhancement of function type hints (callable Typehint)

Since PHP is a weakly typed language, after PHP 5.0, a function type hint has been introduced, supporting objects and arrays, which means checking the parameters of the incoming function for a type check, for example, the following class:

Class Bar {}function foo (bar $foo) {}
The parameters in the function foo specify that the passed in parameter must be an instance of the bar class, or the system will determine an error. It is also possible to make judgments about arrays, such as:

function foo (array $foo) {}foo (Array (    1, 2, 3));//correct, because the array foo (123) is passed in, and//incorrect, not the array function my_function passed in (callable $x)  {     return $x ();}

In PHP 5.4, support for the callable type 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 the right callback function that could be called, as in the following example:

function foo (callable $callback) {}
The

Foo ("false"); Error, because false is not callable type foo ("printf"); Correct foo (function () {}); Correct class A {    static function show () {        }}foo (array (    "A", "show");//correct
Unfortunately, PHP 5.4 still does not support type hints for basic types such as characters, shaping, and so on.


Enhanced Time statistics , high-precision timers

The $_server[' request_time_float ' array variable was introduced, with microsecond accuracy (one out of 10,000 seconds, FLOAT type). is useful for statistical script run times:

Echo ' Executed in ', Round (Microtime (true)-$_server[' request_time_float '], 2)


16. Upload progress bar Upload progress

File Upload Progress Feedback, this requirement is now more and more common, such as large attachment mail. Prior to PHP5.4, we were able to do so through the capabilities provided by APC. Or you can use PECL extension uploadprogress to implement.

Although, they can solve the present problem well, but there are also obvious deficiencies:

    • 1. They all need additional installation (we do not intend to add APC to PHP5.4)
    • 2. They all use local mechanisms to store this information, and APC uses shared memory, while Uploadprogress uses the file system (regardless of NFS), which can cause problems in multiple front-end machines.

From the PHP point of view, the best place to store this information should be the session, first of all it is PHP native support mechanism. Second, it can be configured to store anywhere (multi-machine sharing is supported).

Because of this, Arnaud Le Blanc made an RfC for the progress of the session report upload, and the implementation is now included in the PHP5.4 backbone.

by $_session["Upload_progress_name"] can get the current file upload progress information, combined with Ajax can easily implement the upload progress bar.


Zend Signal in PHP 5.4

In PHP5.4, based on the RFC submitted by Rasmus, a new set of signal processing mechanisms is introduced to enable the signal masking mechanism to be applied to any SAPI and to improve PHP performance in this process.

The new mechanism, called Zend Signal, is the idea of "delayed signal processing" from Yahoo. (Yahoo signal deferring mechanism), and then Facebook added the idea to PHP, in order to boost Php+apache 1 . x PHP calls the performance of Ap_block/ap_unblock.


PHP 5.4 introduced a three-dimensional optimization scheme by Arnaud.

We all know that PHP uses write-time replication to perform performance optimizations on variable replication, whereas in the previous ternary, it is duplicated every time, which can cause performance problems when the operand is a large array:

    
  


Removed attributes

1) Finally, we focus on several features that have been marked as deprecated for several years. These features include Allow_call_time_pass_reference, Define_syslog_variables, highlight.bg, Register_globals, Register_long_ Arrays, Magic_quotes, Safe_mode, Zend.ze1_compatibility_mode, Session.bug_compat42, Session.bug_compat_warn and Y2k_ Compliance

2) The highly criticized Register Globals has been completely removed from PHP. For ten years, this feature has been known for its frequent security breaches. 2002 This feature is set to off by default. PHP5.3, released in 2009, marked this feature as "deprecated", presumably since then, most developers have no longer used it.

3) In addition to these characteristics, magic_quotes may be the greatest danger. In earlier versions, the consequences of magic_quotes errors were not considered, and applications that were simply written and did not take any action to protect themselves from SQL injection attacks were protected by magic_quotes. If you do not verify that you have taken the correct SQLi protection when you upgrade to PHP 5.4, you can cause a security vulnerability.

4) The break and continue statements in PHP can be followed by a parameter to indicate the number of loop layers that jump out. If you do not specify a parameter, it jumps out of the inner loop like VB, C #, or Java. Before PHP 5.4, developers could pass a variable to the break statement, and now only pass constants.

5) PHP allows parameters to be passed by reference. In earlier versions, you could indicate that a variable was passed by reference by adding a decoration to the call point. In PHP 5.4, this option has been removed. Instead, modern PHP programming only needs to be passed by reference when the function is declared. Unlike C #, you do not need to specify the pass by reference at both the Declaration and the invocation point.


Other changes and features

    • There is a new "callable" type hint that is used in cases where a method takes a callback as a parameter.

    • Htmlspecialchars () and htmlentities () are now better able to support Asian characters, and if PHP Default_charset is not explicitly set in the php.ini file, the two functions use UTF-8 instead of iso-8859-1 by default.

    • The session ID is now by default generated by entropy in/dev/urandom (or equivalent), rather than as an option that must be explicitly enabled as in earlier versions.

    • Mysqlnd This bundled MySQL native driver library is now used by default for various extensions that communicate with MySQL, unless the./configure is explicitly overwritten at compile time.

There may be 100 minor changes and features. Upgrading from PHP 5.3 to 5.4 should be extremely smooth, but please read the Migration Guide to make sure. If you upgrade from an earlier version, you may be doing a little more. Review the previous Migration Guide before you start the upgrade.



What is the next step in PHP planning?

We don't have a long-term plan for PHP. PHP will evolve along with the Web. We don't know what the important WEB trends and technologies will be in 5-10 years, but knowing that through our constant pay, PHP will be there.

In the short term, we discuss PHP development through the "Internals" mailing list, and when we reach a consensus on big features, it will evolve into an RFC. You can find the RFC in WIKI.PHP.NET/RFC. Once we have voted to release an excellent set of new features and have implemented and tested these features correctly, we are ready to launch a new version.

PHP develops and maintains a stable market share with the web, which is used by about One-third of all Web sites around the world. This includes not only some of the largest sites, but also a large portion of the smallest sites. I set up PHP on the smallest Web site: Extensions are natural, even expected features, and are highly attractive to engineers, but they are less normal and, in some cases, more difficult. If you find the right balance, and you can use the same code base for your dorm rental and even a company with $ billions of in assets, you really have mastered the language.


The PHP 5.4 version will be the last version that supports Windows XP and Windows 2003 and will no longer provide binary packages for these operating systems in the future.

PHP 5.4 would be is the last series to support Windows XP and Windows2003. We won't provide binary packages for these Windows versionsafter PHP 5.4.


  • Related Article

    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.