New features in PHP 5.5

Source: Internet
Author: User
Tags finally block getmessage

Article turned from: http://wulijun.github.io/2013/07/17/whats-new-in-php-5-5.html

Http://www.cnblogs.com/yjf512/p/3164400.html

Generator (generators)

The builder is one of the most anticipated new features that enable developers to iterate without implementing an iterator interface. Writing a class that implements an iterator interface requires copying a lot of duplicate code, and now using the generator, you can reduce the amount and complexity of the code.

The generator is implemented with the New keyword yield, which resembles a normal function, but unlike a function that returns only a single value, the generator can generate any value. Here is an example of the power of this feature. Consider the range () function in PHP, which returns an array of values between $start and $end, as in the following usage:

<? PHP foreach (Range (01000000 as $number) {    echo $number;}

In this example, the array returned by the range () function consumes a lot of memory (about 100 MB), leaving aside this simple example, in real-world applications, it is often necessary to create huge arrays that consume a lot of time and memory. With the introduction of the generator, we do not have to write an iterator class to solve this problem. The generator does not create a large array, but instead returns a value each time the iteration is made. The above example can be changed to use the generator version:

<? PHP // define a simple range generator 1      {for ($i = $start; $i < $end; $i + = $step) {         //  yield one result at Atime        yield  $i;    }} foreach (Generaterange (01000000 as $number) {    echo $number;}

The result of this code is the same as the first example, but the runtime does not create a large array to hold all the values, so only less than 1K of memory, compared to the original code greatly saves memory consumption.

Password hash

The new password hash API is a very important and practical feature in PHP5.5. Previously, developers had to rely on other crypt () functions, and the documentation for those functions was not quite complete, leading to a lot of misuse. Now the new API is straightforward and easy for developers to implement secure password hashing.

The new API contains functions such as Password_hash () and password_verify (), calling Password_hash ($password, Password_default) to return one using Bcrypt encryption and automatically adding The hash value of the salting. Password_verify ($password, $hash) is called when the password is validated. The API now uses Bcrypt by default and may introduce other new, more secure encryption methods in the future. Developers can adjust the Bcrypt parameters to improve the encryption strength, they can specify the salt value and so on (but the official does not recommend this).

Finally

PHP5.5 started to support the Finally keyword commonly used in exception handling in other languages, and developers can then run the specified code after the try and catch blocks, without having to worry about whether an exception was thrown, and then back to the normal execution stream, before Developers can only copy code in try and catch blocks to complete related task cleanup tasks. For example, you must call Releaseresource () in two places:

<?phpfunction dosomething () {    $resource = Createresource ();    try {        $result = Useresource ($resource);    }    catch (Exception $e) {        releaseresource ($resource);        Log ($e->getmessage ());        Exit ();    }    Releaseresource ($resource);    return $result;}

  

With the finally keyword, you can delete the redundant code:

<? phpfunction dosomething () {    = createresource ();     Try {        = Useresource ($resource);         return $result;    }     Catch (Exception $e) {        log ($e-getMessage ());        Exit ();    }     finally {        releaseresource ($resource);    }}

After the modified code, we simply call the cleanup function Releaseresource () in the finally block, regardless of whether the process eventually goes to the return statement in the try or to the code in the exit,finally in the catch.

Array and string literal dereference

Now the syntax for accessing the array supports the dereference of arrays and string literals:

<? PHP // array Dereferencing-returns 3echo [1357] [1]; // string Dereferencing-returns "L" " Hello " [3];

This feature is mainly to enhance the consistency of the language, we usually write code behavior may not have a small impact, but in some scenarios is very convenient to use:

<?  "abcdefg0123456789"[Mt_rand (0)];

Empty () supports function calls and expressions

The language structure of empty () is beginning to support use in function calls and expressions, such as empty ($object->getproperty ()). This allows you to use empty () to determine the return value of a function without first assigning the return value to a temporary variable and then using empty () for the temporary variable.

Class name resolution

After introducing a namespace from PHP5.3, it is commonplace to use it to organize the class structure in a PHP project, but it is very difficult to retrieve the fully qualified class name with a namespace, such as:

<?  New reflectionclass ("Foo");

This code will fail because it will look up the class Foo from the global namespace, not the specified namespace. PHP5.5 introduces the class keyword, which allows you to get the fully qualified class name:

<?  New Reflectionclass (Foo::class);

In the above code, foo:class resolves to "Namespaced\class\foo".

foreach Improvements

The list () language structure makes it easy to assign values from an array to a set of variables, such as:

<?  = ["Sea""blue"];list ($object, $ Description) = $values; // returns "The Sea is Blue" " The $object is $description ";

You can now start by using the list () when foreach iterates through a multidimensional array:

<?Php$data= [    ["Sea","Blue"],    ["Grass","Green"]]; foreach($data asList ($Object, $description)) {echo"The $object is $description \ n";}/*outputs:the Sea is bluethe grass is green*/

This feature makes the traversal of nested arrays much easier and more concise, and the Foreach loop begins to support non-scalar values as the iterator's key, meaning that the element's key can be a type value other than a string and an integer.

Conclusion

PHP5.5 provides a number of improvements to PHP's efficient development, in addition to these new features, but also modified a large number of bugs, specific reference changelog

Original link: http://phpmaster.com/whats-new-in-php-5-5/

 

New features in PHP 5.5

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.