New features for each version of PHP

Source: Internet
Author: User
Tags deprecated intl rfc scalar traits zend framework

Because of the new version of PHP, some of the new features must be understood, and some can be used in development, if not used, then why upgrade PHP version, it seems to be a bit more than the candle!
So tidy up some features, may not be complete, to be added
What's new in PHP 5.3
A What's new in PHP 5.3
1. Support Namespaces (Namespace)
2. Support delay static binding (late static bindings)
3. Support Goto Statement
4. Support closures, lambda/anonymous functions
5. Added two magic methods __callstatic () and __invoke ()
6. New Nowdoc syntax
7. Const can also be used to define constants outside the class
8. Ternary operators add a quick way to write:
9. HTTP status code is considered to be successful in the 200-399 range
10. Support Dynamic Call static method
1. Support Namespaces (Namespace)
There is no doubt that the namespace is the most important new feature brought by PHP5.3. With the concept of namespaces, it is easier to design a flexible structure when developing large sites, while avoiding conflicting class names or variable names in different packages.
Before PHP5.3, the usual way to divide the package is to separate the code files by their directory names, and the class names in the code to represent the directories with underscores _. For example
<!--
<?php
Class Zend_db_table_select {}
The file that represents the current class is located in the Zend/db/table/select directory
?>
-

This naming method is widely used by pear, Zend framework and various PHP projects. While this approach avoids conflicting class names in different packages or class libraries, it can be cumbersome and cumbersome to write code.
In PHP5.3, you only need to specify a different namespace, and the delimiter for the namespace is the backslash \.
select.php

<!--
<?php
namespace Zend\db\table;
Class Select {}
?>
-
This way, even if a class named Select exists under other namespaces, the program does not create a conflict at the time of the call. The readability of the code has also increased.

Calling methods
call.php

<!--
<?php
namespace Zend\db;
Include (' select.php ');
$s = new zend\db\table\select ();
$s->test ();
?>
-
2. Support delay static binding (late static bindings)
In PHP5, we can use the Self keyword or __class__ to determine or invoke the current class in a class. But there is a problem, if we are called in the subclass, the resulting result will be the parent class. Since the parent class is inherited, the static member is already bound. For example:

<!--
<?php
Class A {
public static function who () {
Echo __class__;
}
public static function test () {
Self::who ();
}
}


Class B extends A {
public static function who () {
Echo __class__;
}
}
B::test ();
?>
-
The result of the above code output is:
A
This is different from what we expected, and we originally wanted the corresponding result of the subclass.
PHP 5.3.0 adds a static keyword to refer to the current class, which implements deferred static binding:

<!--
<?php
Class A {
public static function who () {
Echo __class__;
}
public static function test () {
Static::who (); This implements a static binding of delay
}
}
Class B extends A {
public static function who () {
Echo __class__;
}
}

B::test ();
?>

-
The result of the above code output is:
B
3. Support Goto Statement
In most computer programming languages, the unconditional turn statement Goto is supported, and when the program executes to a goto statement, it moves to the program location indicated by the label in the Goto statement to continue execution. Although the goto statement may cause the program process to be unclear and less readable, in some cases it has its own unique convenience, such as breaking deep nested loops and if statements.

<!--

<?php

Goto A;

Echo ' Foo ';

A:

Echo ' Bar ';

For ($i =0, $j =50; $i <100; $i + +) {

while ($j-) {

if ($j ==17) goto end;

}

}

echo "i = $i";

End

Echo ' J hit 17 ';

?>

-
4. Support closures, lambda/anonymous functions
The concept of closure (Closure) functions and lambda functions comes from the field of functional programming. For example, JavaScript is one of the most common languages that support closures and lambda functions.
In PHP, we can also create functions through create_function () when the code is running. But there is a problem: The created function is compiled only at run time, not with other code being compiled into execution code at the same time, so we cannot use execution code caching like APC to improve the efficiency of code execution.


In PHP5.3, we can use the lambda/anonymous function to define a number of functions that are temporarily used (that is, disposable) to function as callback functions for functions such as Array_map ()/array_walk ().

<!--

<?php

echo Preg_replace_callback (' ~-([A-z]) ~ ', function ($match) {

return Strtoupper ($match [1]);

}, ' Hello-world ');

Output HelloWorld

$greet = function ($name)

{

printf ("Hello%s\r\n", $name);

};

$greet (' World ');

$greet (' PHP ');

//... In a class

$callback = function ($quantity, $product) use ($tax, & $total) {

$pricePerItem = constant (__class__. "::P rice_". Strtoupper ($product));

$total + = ($pricePerItem * $quantity) * ($tax + 1.0);

};

Array_walk ($products, $callback);

?>

-

5. Added two magic methods __callstatic () and __invoke ()
PHP originally had a magic method __call (), and the Magic method would be called automatically when the code called a non-existent method of the object. The new __callstatic () method is used only for static class methods. The __callstatic () Magic method is called automatically when attempting to invoke a static method that does not exist in the class.

<!--

<?php
Class Methodtest {
Public Function __call ($name, $arguments) {
Parameter $name case sensitive
echo "Call object method ' $name '". Implode ('---', $arguments). "\ n";
}
/** PHP 5.3.0 or later of this method is valid */

public static function __callstatic ($name, $arguments) {
Parameter $name case sensitive
echo "calls the static method ' $name '". Implode ('---', $arguments). "\ n";
}

}
$obj = new Methodtest;

$obj->runtest (' Call through object ');

Methodtest::runtest (' static call '); As of PHP 5.3.0
?>
-
The above code executes after the output is as follows:
Call the object method ' Runtest ' –-call the static method ' Runtest ' –-a static call through an object call
The __invoke () method is called automatically when the object is called as a function.
01
<!--
02
<?php
03
Class Methodtest {
04
Public Function __call ($name, $arguments) {
05
Parameter $name case sensitive
06
echo "Calling object method ' $name '"
07
. Implode (', ', $arguments). "\ n";
08
}
09

10
/** PHP 5.3.0 or later of this method is valid */
11
public static function __callstatic ($name, $arguments) {
12
Parameter $name case sensitive
13
echo "Calling static method ' $name '"
14
. Implode (', ', $arguments). "\ n";
15
}
16
}
17

18
$obj = new Methodtest;
19
$obj->runtest (' in object context ');
20

21st
Methodtest::runtest (' in static context '); As of PHP 5.3.0
22
?>
23
-
6. New Nowdoc syntax
Usage is similar to Heredoc, but uses single quotation marks. Heredoc need to be declared by using double quotation marks.
Nowdoc does not do any variable parsing and is ideal for passing a piece of PHP code.
01
<!--
02
<?php
03
Nowdoc single quotes after PHP 5.3 support
04
$name = ' MyName ';
05
echo <<< ' EOT '
06
My name is "$name".
07
EOT;
08
The above code outputs My name is "$name". (where the variable is not parsed)
09
Heredoc without quotation marks
10
Echo <<<foobar
11
Hello world!
12
FOOBAR;
13
or double quotes after PHP 5.3 support
14
echo <<< "FOOBAR"
15
Hello world!
16
FOOBAR;
17
?>
18
-
Supports initialization of static variables, class members, and class constants through Heredoc.
01
<!--
02
<?php
03
static variables
04
function foo ()
05
{
06
Static $bar = <<<label
07
Nothing is here ...
08
LABEL;
09
}
10

11
Class members, constants
12
Class Foo
13
{
14
Const BAR = <<<foobar
15
Constant Example
16
FOOBAR;
17

18
Public $baz = <<<foobar
19
Property Example
20
FOOBAR;
21st
}
22
?>
23
-
7. Const can also be used to define constants outside the class
The constants defined in PHP are usually in this way:
1
<!--
2
<?php
3
Define ("CONSTANT", "Hello World");
4
?>
5
-
And a new way of defining constants is added:
1
<!--
2
<?php
3
Const CONSTANT = ' Hello world ';
4
?>
5
-
8. Ternary operator adds a quick way to write
1
<!--
2
?:
3
-
The original format is (EXPR1)? (EXPR2): (EXPR3)
If the expr1 result is true, the result of the EXPR2 is returned.
PHP5.3 New Writing method, you can omit the middle part, written as expr1?: EXPR3
Returns the result of EXPR1 if the expr1 result is true
9. HTTP status code is considered to be successful in the 200-399 range
10. Support Dynamic Call static method
01
<!--

<?php

Class test{

public static function Testgo ()

{

echo "gogo!";

}

}

$class = ' Test ';

$action = ' Testgo ';

$class:: $action (); Output "gogo!"

?>

-
11. Support for nesting exception handling (Exception)
12. New garbage Collector (GC), and enabled by default
Two Other notable changes in the PHP5.3
1. Fixed a lot of bugs
2. Improved PHP performance
3. Variables can be used in php.ini
4. Mysqlnd into the core extension theoretically, the extension accesses MySQL faster than the previous MySQL and mysqli extensions (see http://dev.mysql.com/downloads/connector/php-mysqlnd/)
5. Extensions such as Ext/phar, Ext/intl, Ext/fileinfo, Ext/sqlite3, and Ext/enchant are published by default with PHP bindings. Where Phar can be used to package PHP programs, similar to the jar mechanism in Java.
6. Ereg Regular expression functions are no longer available by default, use faster pcre regular expression functions

What's new in PHP 5.4
1. buid-in Web server has built-in a simple Web servers
The current directory as root document requires only this command:
# php-s localhost:3300
You can also specify a different path:
# php-s Localhost:3300-t/path/to/root
You can also specify a route:
# php-s localhost:3300 router.php
2.Traits
Traits provides a flexible code reuse mechanism, that is, unlike interface, you can only define methods but not implement them, and you cannot simply inherit as class. As for how to use in practice, we need to think deeply.
Magic constant for __TRAIT__
3. Short array Syntax syntax
1
<!--
2
$arr = [1, ' Tsing ', ' tsingpost.com '];
3
$array = [
4
"foo" = "Bar",
5
"Bar" = "foo"
6
];
7
-
4. Array dereferencing values
01
<!--
02
function MyFunc () {
03
return Array (1, ' Tsing ', ' tsingpost.com ');
04
}
05
I think dereferencing is more convenient than an array of short syntax, which we used to do:
06
$arr = MyFunc ();
07
echo $arr [1];
08
In PHP5.4, this is the case:
09
Echo MyFunc () [1];
10
Other:
11
$name = Explode (",", "Tsings,male") [0];
12
Explode (",", "Tsings,male") [3] = "Phper";
13
-
5. Upload Progress
SESSION provides upload progress support, through the $_session["Upload_progress_name" can get the current file upload progress information, combined with Ajax can easily implement the upload progress bar.
6. Jsonserializable Interface
An instance of a class that implements the Jsonserializable interface calls the Jsonserialize method before the Json_encode is serialized, rather than directly serializing the object's properties.
7. Use MYSQLND by default
1
<!--
2
Now MySQL, mysqli, Pdo_mysql uses the MYSQLND local library by default, which is required before PHP5.4:
3
$./configure--with-mysqli=mysqlnd
4
Right now:
5
$./configure--with-mysqli
6
-
8. Instantiating classes
1
<!--
2
Class test{
3
Function Show () {
4
return ' test ';
5
}
6
}
7
Echo (new test ())->show ();
8
-
9. Support CLASS::{EXPR} () syntax
1
<!--
2
foreach ([New Human ("Gonzalo"), New Human ("Peter")] as $human) {
3
echo $human->{' Hello '} ();
4
}
5
-
10.Callable Typehint
01
<!--
02
function foo (callable $callback) {
03
}
04
The
05
Foo ("false"); Error because false is not a callable type
06
Foo ("printf"); That's right
07
Foo (function () {}); That's right
08
Class A {
09
static function Show () {
10
}
11
}
12
Foo (Array ("A", "show")); That's right
13
-
11. Enhancement of function type hints
01
<!--
02
Since PHP is a weakly typed language, after PHP 5.0, a function type hint is introduced, meaning that the parameters in the incoming function are type-checked, for example, a class like the following:
03
Class Bar {
04
function foo (bar $foo) {
05
}
06
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:
07
function foo (array $foo) {
08
}
09
}
10
Foo (Array (1, 2, 3)); Correct, because an array is passed in
11
Foo (123); Incorrect, not array passed in
12
-
12. The new $_server["Request_time_float" is added, which is used to count the service request time and is represented by MS
1
<!--
2
echo "Script execution Time", round (Microtime (true)-$_server["Request_time_float"], 2), "s";
3
-
13. Let JSON understand Chinese (json_unescaped_unicode)
1
<!--
2
Echo Json_encode ("Chinese", Json_unescaped_unicode);
3
Chinese
4
-
14. Binary Direct (binary number format)
1
<!--
2
$bin = 0b1101;
3
Echo $bin;
4
13
5
-
PHP 5.4.0 performance has been significantly improved to fix more than 100 bugs.
Register_globals, magic_quotes, and safe mode were abolished.
It is also worth mentioning that multi-byte support is enabled by default,
Default_charset has changed from Iso-8859-1 to UTF-8.
Default Send "content-type:text/html; Charset=utf-8 ",
You no longer have to write meta tags in html, and you don't need to send extra headers for UTF-8 compatibility.
Removed attributes
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
In addition to these features, Magic_quotes can be the biggest 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.
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's new in PHP 5.5
The new features and proposals list are quite large and not sorted by importance. So, if you don't want to read through it, here are four features I personally are most excited about:
: A simple Password hashing API
: Scalar type hint
: Getter and setter
: Generator
Now, let's take a look at the features that PHP5.5 might add:
1. Discard support for Windows XP and 2003
2. Discard the E modifier
The e modifier is an indication that the Preg_replace function is used to evaluate the replacement string as PHP code, rather than just a simple string substitution. Unsurprisingly, this kind of behavior will continue to have security problems. This is why using this modifier in PHP5.5 throws a deprecated warning. As an alternative, you should use the Preg_replace_callback function. You can find more information about this change from the RfC.
3. New functions and classes
01
<!--
02
Boolval ()
03
PHP has implemented the functions of Strval, Intval, and Floatval. In order to achieve consistency, the Boolval function is added. It can be calculated as a Boolean value or as a callback function.
04

05
HASH_PBKDF2 ()
06
PBKDF2 full name "password-based Key derivation Function 2", just like its name, is an algorithm that derives the encryption key from the password. This requires a cryptographic algorithm and can also be used to hash the password. More extensive illustration and usage examples
07

08
Array_column ()
09
$userNames = Array_column ($users, ' name ');
10
is the same as
11
$userNames = [];
12
foreach ($users as $user) {
13
$userNames [] = $user [' name '];
14
}
15

16
Intl Extension
17
There will be many improvements to the intl extension. For example, there will be new Intlcalendar,intlgregoriancalendar,intltimezone,intlbreakiterator,intlrulebasedbreakiterator, Intlcodepointbreakiterator class. Before I actually didn't know there was so much about the intl extension, if you want to know more, I suggest you go to the latest announcements for calendar and Breakiterator.
18
-
4. A simple password hashing API
01
<!--
02
$password = "Foo";
03
Creating the Hash
04
$hash = Password_hash ($password, Password_bcrypt);
05
Verifying a password
06
if (Password_verify ($password, $hash)) {
07
Password correct!
08
} else {
09
Password wrong!
10
}
11
-
5. New language features and enhancements.
01
<!--
02
Constant reference
03
Constant reference means that arrays can manipulate strings and array literals directly. Give two examples:
04
function randomhexstring ($length) {
05
$str = ";
06
for ($i = 0; $i < $length; + + $i) {
07
$str. = "0123456789abcdef" [Mt_rand (0, 15)]; Direct dereference of String
08
}
09
}
10
function Randombool () {
11
return [False, True][mt_rand (0, 1)]; Direct dereference of array
12
}
13
I don't think this feature will be used in practice, but it makes the language more consistent. See RFC.
14
-
6. Call the Empty () function (and other expressions) to work together
Currently, empty () language constructs can only be used in variables, not in other expressions.
An error will be thrown in the specific code like empty ($this->getfriends ()). As PHP5.5 this will become a valid code
7. Get the full category name
1
<!--
2
The functionality of the alias class and namespace short version of the namespace is introduced in PHP5.3. Although this does not apply to string class names
3
Use Some\deeply\nested\namespace\foobar;
4
Does not work, because this would try to use the global FooBar class
5
$reflection = new Reflectionclass (' FooBar ');
6
Echo Foobar::class;
7
To solve this problem, use the new Foobar::class syntax, which returns the full category name of the class
8
-
8. Parameter jumps
1
<!--
2
If you have a function that accepts multiple optional parameters, there is currently no way to change only the last parameter, and all other parameters are the default values.
3
On the RFC example, if you have a function like this:
4
function Create_query ($where, $order _by, $join _type= ", $execute = False, $report _errors = True) {...}
5
Then there is no way to set $report_errors=false, while the other two are the default values. In order to solve the problem of this jumping parameter is proposed:
6
Create_query ("Deleted=0", "name", default, Default, False);
7
I personally do not particularly like this proposal. In my eyes, the code needs this function, but it's not designed properly. A function should not have 12 optional parameters.
8
-
9. Scalar type hints
01
<!--
02
The scalar type hint was originally planned to enter 5.4, but was not done because of a lack of consensus. For more information on why scalar type hints are not being made into PHP, see: Scalar type hints are more difficult than you think.
03
For PHP5.5, the discussion of the scalar type prompt is another occurrence, which I think is a pretty good proposition.
04
It needs to specify the type by entering a value. For example: 123,123.0, "123" is a valid int parameter input, but "Hello World" is not. This is consistent with the behavior of the intrinsic function.
05
function foo (int $i) {...}
06
Foo (1); $i = 1
07
Foo (1.0); $i = 1
08
Foo ("1"); $i = 1
09
Foo ("1abc"); Not yet clear, maybe $i = 1 with notice
10
Foo (1.5); Not yet clear, maybe $i = 1 with notice
11
Foo ([]); Error
12
Foo ("abc"); Error
13
-
10.Getter and Setter
01
<!--
02
If you never like to write these getxyz () and SETXYZ ($value) methods, then this should be your most popular change. It is proposed to add a new syntax to define the setting/reading of a property:
03
<?php
04

05
Class TimePeriod {
06
Public $seconds;
07

08
Public $hours {
09
get {return $this->seconds/3600;}
10
set {$this->seconds = $value * 3600;}
11
}
12
}
13
$timePeriod = new TimePeriod;
14
$timePeriod->hours = 10;
15
Var_dump ($timePeriod->seconds); Int (36000)
16
Var_dump ($timePeriod->hours); Int (10)
17
There are, of course, more features, such as read-only properties. If you want to know more, see RFC.
18
-
11. Generator
01
<!--
02
Currently, custom iterators are seldom used because their implementation requires a lot of boilerplate code. The generator solves this problem and provides a simple boilerplate code to create iterators.
03
For example, you can define a range function as an iterator:
04
<?php
05
function *xrange ($start, $end, $step = 1) {
06
for ($i = $start; $i < $end; $i + = $step) {
07
Yield $i;
08
}
09
}
10
foreach (Xrange (Ten) as $i) {
11
// ...
12
}
13
The Xrange function above has the same behavior as the built-in function, but it is a little different: instead of returning all the values of an array, it returns the dynamically generated value of an iterator.
14
-
12. List parsing and builder expressions
01
<!--
02
List parsing provides a simple way to perform small-scale operations on arrays:
03
$firstNames = [foreach ($users as $user) yield $user->firstname];
04
The above list resolution equals the following code:
05
$firstNames = [];
06
foreach ($users as $user) {
07
$firstNames [] = $user->firstname;
08
}
09
You can also filter arrays like this:
10
$underageUsers = [foreach ($users as $user) if ($user->age <) yield $user];
11
The generator expression is similar, but returns an iterator (for dynamically generated values) instead of an array.
12
-
13.finally keywords
1
<!--
2
This is the same as finally in Java, the classic try ... catch ... finally three-segment exception handling.
3
-
14.foreach Support List ()

<!--

To iterate over an array of arrays, you need to use two foreach before, and now you only need to use the Foreach + list, but the number of arrays in this array needs to be the same. Look at the example of a document and see it.

$array = [

[1, 2],

[3, 4],

];

foreach ($array as list ($a, $b)) {

echo "A: $a; B: $b \ n ";

}

-
15. Added Opcache extension
Using Opcache will improve PHP performance, and you can add this optimization to the same static compilation (–enable-opcache) or dynamic extension (zend_extension) as any other extension.
16. The non-variable array and string can also support the subscript to obtain the

<!--

echo Array (1, 2, 3) [0];

echo [1, 2, 3][0];

echo "Foobar" [2];

-

New features for each version of PHP

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.