New features in PHP 5.4 and summary of deprecated function functions

Source: Internet
Author: User
Tags apc deprecated new set parse error small web server drupal zend framework
Summary of new features and deprecated functional functions in PHP 5.4:

First, PHP5.4 new features

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.

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 may be the most talked about feature in PHP 5.4-they are treated as 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;      // ...  }    Singleton method is now available for both classes  a::getinstance ();  B::getinstance ();   

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:

$a = [1, 2, 3];  $b = [' foo ' = ' orange ', ' bar ' and ' Apple '];   

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:

 
  


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;      }  }     $X = (new foo)->setx ()->getx ();  Echo $X; 20   

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);      }  }     Echo (New foo ([1, [4, 5], 3])) [1][0];   

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);    }} $a = new Foo (' Bar ');;  $func = $a->getprinter ();  $func (); Outputs:bar   

Note that the closure access $this->prop this private property. By default, closures in PHP use pre-binding-which 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:

$a = new Foo (' Bar ');  $b = new Foo (' Pickle ');  $func = $a->getprinter ();  $func (); Outputs:bar  $func = $func->bindto ($b);  $func (); Outputs:pickle   

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:8000    php 5.4.0 Development Server started at Sun Mar one 13:27:09 Listening on    localhost:80    Document root Is/home/rasmus press    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.php    php 5.4.0 Development Server started at Sun Mar 13:28:01    Liste Ning on localhost:8080    Document root Is/tmp/web press    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) public    int Write (string $sessionid, String $sessiondata)  }  Session_set_save_h Andler (new Mysessionhandler);   

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 Lin E 1  

After improvement:

% Php-r ' class ABC Foo '    Parse error:syntax error, unexpected ' foo ' (t_string), expecting ' {'     Command line cod E 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:

$a = [n/a];  echo $a;   

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

14. 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 incoming array is    foo (123);//incorrect, not an array    passed in function my_function (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.


15. 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:

  

Second, the characteristics of the deletion

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.

Iii. 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.

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.

  • 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.