Home >Backend Development >PHP Tutorial >Detailed explanation of new features from PHP5.2 to 5.6, new features in php5.25.6_PHP Tutorial

Detailed explanation of new features from PHP5.2 to 5.6, new features in php5.25.6_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:23:171025browse

Detailed explanation of the new features of PHP5.2 to 5.6, new features of php5.25.6

As of now (2014.2), the latest stable version of PHP is PHP5.5, but almost half of the users are still using PHP5.2 which is no longer maintained [Note], and the remaining half of the users are using PHP5.3 [Note] ].
Because of PHP's painful syntax that "gathers the strengths of hundreds of schools of thought" and the poor community atmosphere, many people are not interested in new versions and new features.

This article will introduce the new features added from PHP5.2 to PHP5.6.

Before PHP5.2: autoload, PDO and MySQLi, type constraints
PHP5.2: JSON support
PHP5.3: Deprecated features, anonymous functions, new magic methods, namespaces, late static binding, Heredoc and Nowdoc, const, ternary operator, Phar
PHP5.4: Short Open Tag, array abbreviation, Traits, built-in web server, details modified
PHP5.5: yield, list() is used for foreach, details modified
PHP5.6: Constant enhancement, variable function parameters, namespace enhancement

Note: Support has been discontinued in January 2011: http://www.php.net/eol.php
Note: http://w3techs.com/technologies/details/pl-php/5/all

Before PHP5.2

(Before 2006)
By the way, let me introduce the features that have already appeared in PHP5.2 but are worth introducing.
autoload
Everyone may know the __autoload() function. If this function is defined, then when an undefined class is used in the code, the function will be called. You can load the corresponding class implementation file in this function. Such as:

Copy code The code is as follows:

function __autoload($classname) {
require_once("{$classname}.php")
}

But this function is no longer recommended because there can only be one such __autoload() function in a project because PHP does not allow functions with duplicate names. But when you use some class libraries, you will inevitably need multiple autoload functions, so spl_autoload_register() replaces it:

Copy code The code is as follows:

spl_autoload_register(function($classname){
require_once("{$classname}.php")
});

spl_autoload_register() will register a function into the autoload function list. When an undefined class appears, SPL [Note] will call the registered autoload functions one by one in the reverse order of registration, which means you can use spl_autoload_register () Register multiple autoload functions.

Note: SPL: Standard PHP Library, standard PHP library, is designed to solve some classic problems (such as data structure).
PDO and MySQLi
That is, PHP Data Object, PHP data object, which is PHP's new database access interface.

According to the traditional style, accessing the MySQL database should look like this:

Copy code The code is as follows:

// Connect to the server and select the database
$conn = mysql_connect("localhost", "user", "password");
mysql_select_db("database");

//Execute SQL query
$type = $_POST['type'];
$sql = "SELECT * FROM `table` WHERE `type` = {$type}";
$result = mysql_query($sql);

//Print results
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach($row as $k => $v)
           print "{$k}: {$v}n";
}

// Release the result set and close the connection
mysql_free_result($result);
mysql_close($conn);

In order to make the code database independent, that is, a piece of code is applicable to multiple databases at the same time (for example, the above code is only applicable to MySQL), PHP officially designed PDO.
In addition, PDO also provides more functions, such as:
•Object-oriented style interface
•SQL precompilation (prepare), placeholder syntax
•Higher execution efficiency, as an official recommendation, there are special performance optimizations
•Supports most SQL databases, no need to change the code when changing the database

The above code implemented using PDO will look like this:

Copy code The code is as follows:

// Connect to database
$conn = new PDO("mysql:host=localhost;dbname=database", "user", "password");

//Pre-compile SQL, bind parameters
$query = $conn->prepare("SELECT * FROM `table` WHERE `type` = :type");
$query->bindParam("type", $_POST['type']);

//Execute the query and print the results
foreach($query->execute() as $row)
{
foreach($row as $k => $v)
           print "{$k}: {$v}n";
}

PDO is officially recommended as a more general database access method. If you have no special needs, then you'd better learn and use PDO.
But if you need to use advanced features unique to MySQL, then you may want to try MySQLi, because PDO does not include those unique features of MySQL in order to be used on multiple databases at the same time.

MySQLi is an enhanced interface for MySQL. It provides both process-oriented and object-oriented interfaces. It is also the currently recommended MySQL driver. The old C-style MySQL interface will be closed by default in the future.
Compared with the above two pieces of code, the usage of MySQLi does not have many new concepts. Examples will not be given here. You can refer to the PHP official website documentation [Note].

Note: http://www.php.net/manual/en/mysqli.quickstart.php

Type constraints

The type of parameters can be restricted through type constraints, but this mechanism is not perfect. Currently it only applies to classes, callable (executable types) and arrays (arrays), and does not apply to string and int.

Copy code The code is as follows:

// Limit the first parameter to MyClass, the second parameter to the executable type, and the third parameter to the array
function MyFunction(MyClass $a, callable $b, array $c)
{
// ...
}

PHP5.2
(2006-2011)

JSON support

Including json_encode(), json_decode() and other functions. JSON is a very commonly used data exchange format in the Web field and can be directly supported by JS. JSON is actually part of the JS syntax.
JSON series functions can convert array structures in PHP into JSON strings:

Copy code The code is as follows:

$array = array("key" => "value", "array" => array(1, 2, 3, 4));
$json = json_encode($array);
echo "{$json}n";

$object = json_decode($json);
print_r($object);

Output:

Copy code The code is as follows:

{"key":"value","array":[1,2,3,4]}
stdClassObject
(
[key] => value
[array] => Array
(
                                  [0] => 1
                                  [1] => 2
                                                                                [2] => 3
                                                                                                  [3] => 4
)
)

It is worth noting that json_decode() will return an object instead of an array by default. If you need to return an array, you need to set the second parameter to true.
PHP5.3
(2009-2012)

PHP5.3 is a very big update, adding a lot of new features and also making some modifications that are not backward compatible.

Deprecated Features

The following features are deprecated. If enabled in the configuration file, PHP will issue a warning at runtime.
Register Globals
This is an option (register_globals) in php.ini. When turned on, all form variables ($_GET and $_POST) will be registered as global variables.
Look at the example below:

Copy code The code is as follows:

if(isAuth())
$authorized = true;
if($authorized)
include("page.php");

When this code passes verification, it sets $authorized to true. Then it decides whether to display the page based on the value of $authorized.

But since $authorized is not initialized to false in advance, when register_globals is turned on, it is possible to access /auth.php?authorized=1 to define the variable value and bypass authentication.

This feature is a historical issue and was turned off by default in PHP4.2 and removed in PHP5.4.

Magic Quotes

Corresponds to the option magic_quotes_gpc in php.ini. This feature is also a historical issue and has been removed in PHP5.4.

This feature will escape all user input, which looks good. We mentioned escaping user input in Chapter 1.
But PHP doesn't know which input will go into SQL, which input will go into Shell, and which input will be displayed as HTML, so many times this escaping will cause confusion.

Safe Mode

Many web hosting providers use Safe Mode to isolate multiple users, but Safe Mode has many problems. For example, some extensions do not control permissions according to Safe Mode.
PHP officially recommends using the operating system mechanism for permission isolation, allowing the web server to run the PHP interpreter with different user permissions. Please refer to the principle of least privilege in Chapter 1.

Anonymous function

Also called closures, they are often used to temporarily create an unnamed function for callback functions and other purposes.

Copy code The code is as follows:

$func = function($arg)
{
Print $arg;
};
$func("Hello World");

The above code defines an anonymous function and assigns it to $func.
You can see that the function keyword is still used to define anonymous functions, but the function name is omitted and the parameter list is directly used.

Then we call the anonymous function stored in $func.

Anonymous functions can also use the use keyword to capture external variables:

Copy code The code is as follows:

function arrayPlus($array, $num)
{
array_walk($array, function(&$v) use($num){
        $v += $num;
});
}

The above code defines an arrayPlus() function (this is not an anonymous function), which adds a specified number ($num) to each item in an array ($array).

In the implementation of arrayPlus(), we use the array_walk() function, which will execute a callback function for each item of an array, which is the anonymous function we defined.
After the parameter list of the anonymous function, we use the use keyword to capture $num outside the anonymous function into the function so that we know how much should be added.
Magic methods: __invoke(), __callStatic()
PHP's object-oriented system provides several "magic methods" to implement "overloading" similar to that in other languages, such as triggering a magic method when accessing non-existent properties or methods.

With the addition of anonymous functions, PHP introduces a new magic method __invoke().
This magic method is called when an object is called as a function:

Copy code The code is as follows:

class A
{
Public function __invoke($str)
{
           print "A::__invoke(): {$str}";
}
}
$a = new A;
$a("Hello World");

The output is undoubtedly:
A::__invoke(): Hello World

__callStatic() will be called when calling a non-existent static method.
Namespace
PHP's namespace has an extremely painful syntax that is unprecedented and unprecedented:

Copy code The code is as follows:

// The delimiter of the namespace is a backslash, and the declaration statement must be on the first line of the file.
// The namespace can contain any code, but only **classes, functions, constants** are affected by the namespace.
namespace XXOOTest;
// The fully qualified name of this class is XXOOTestA, where the first backslash indicates the global namespace.
class A{}
// You can also define a second namespace in the existing file, and the rest of the code will be located in OtherTest2 .
namespace OtherTest2;
// Instantiate objects from other namespaces:
$a = new XXOOTestA;
class B{}
// You can also define a third namespace using curly braces
namespace Other {
// Instantiate objects from sub-namespaces:
$b = new Test2B;
// Import names from other namespaces and rename them,
// Note that only classes can be imported, not functions and constants.
Use XXOOTestA as ClassA
}

For more introduction to the syntax of namespace, please see the official website [Note].

The namespace is often used together with autoload to automatically load class implementation files:

Copy code The code is as follows:

spl_autoload_register(
function ($class) {
spl_autoload(str_replace("\", "/", $class));
}
);

When you instantiate a class XXOOTestA, the fully qualified name of the class will be passed to the autoload function. The autoload function replaces the namespace separator (backslash) in the class name with a slash and includes the corresponding document.
This enables hierarchical storage of class definition files and automatic loading on demand.

Note: http://www.php.net/manual/zh/language.namespaces.php
Late static binding
PHP's OPP mechanism has inheritance and virtual function-like functions, such as the following code:

Copy code The code is as follows:

class A
{
Public function callFuncXXOO()
{
Print $this->funcXXOO();
}
Public function funcXXOO()
{
         return "A::funcXXOO()";
}
}
class B extends A
{
Public function funcXXOO()
{
         return "B::funcXXOO";
}
}
$b = new B;
$b->callFuncXXOO();

The output is:
B::funcXXOO

As you can see, when $this->funcXXOO() is used in A, the "virtual function" mechanism is reflected, and what is actually called is B::funcXXOO().
However, if you change all functions to static functions:

Copy code The code is as follows:

class A
{
static public function callFuncXXOO()
{
          print self::funcXXOO();
}
static public function funcXXOO()
{
         return "A::funcXXOO()";
}
}
class B extends A
{
static public function funcXXOO()
{
         return "B::funcXXOO";
}
}
$b = new B;
$b->callFuncXXOO();

The situation is not so optimistic, the output is:
A::funcXXOO()

Copy code This is because the semantics of self is originally "the current class", so PHP5.3 gives the static keyword a new function: late static binding:

Copy code The code is as follows:

class A
{
static public function callFuncXXOO()
{
          print static::funcXXOO();
}
// ...
}
// ...

This will output as expected:
B::funcXXOO

Heredoc and Nowdoc
PHP5.3 brings some improvements to Heredoc and Nowdoc, both of which are used to embed large strings in PHP code.

Heredoc behaves like a double-quoted string:

Copy code The code is as follows:

$name = "MyName";
echo <<< TEXT
My name is "{$name}".
TEXT;

Copy code Heredoc starts with three left angle brackets, followed by an identifier (TEXT), and ends with an identifier of the same top space (cannot be indented).
Just like double quoted strings, variables can be embedded within them.

Heredoc can also be used for function parameters and class member initialization:

Copy code The code is as follows:

var_dump(<< Hello World
EOD
);
class A
{
const xx = <<< EOD
Hello World
EOD;
Public $oo = <<< EOD
Hello World
EOD;
}


Nowdoc behaves like a single-quoted string and cannot embed variables in it. The only difference from Heredoc is that the identifier after the three left angle brackets must be enclosed in single quotes:

Copy code The code is as follows:

$name = "MyName";
echo <<< 'TEXT'
My name is "{$name}".
TEXT;

Output:
My name is "{$name}".

Use const to define constants
PHP 5.3 supports the use of const to define constants in both the global namespace and classes.

Old style:
define("XOOO", "Value");

New style:

const XXOO = "Value";

The const form only applies to constants, not expressions that can be evaluated at runtime:

Copy code The code is as follows:

// Correct
const XXOO = 1234;
// Error
const XXOO = 2 * 617;

Abbreviated form of ternary operator
Old style:

echo $a ? $a : "No Value";

can be abbreviated as:

echo $a ?: "No Value";

That is, if the second part of the ternary operator is omitted, the first part will be used instead by default.
Phar
Phar is PHP Archive. It was originally just a library in Pear. It was later rewritten as a C extension in PHP5.3 and built into PHP.
Phar is used to package multiple .php scripts (and other files as well) into a .phar compressed file (usually in ZIP format).
The purpose is to imitate Java's .jar, no, the purpose is to make publishing PHP applications more convenient. It also provides functions such as digital signature verification.

.phar files can be interpreted and executed by the PHP engine just like .php files. At the same time, you can also write code like this to include (require) the code in .phar:

Copy code The code is as follows:

require("xxoo.phar");
require("phar://xxoo.phar/xo/ox.php");

For more information, please visit the official website [Note].

Note: http://www.php.net/manual/zh/phar.using.intro.php
PHP5.4
(2012-2013)
Short Open Tag
Short Open Tag is always available since PHP5.4.
Here we will focus on the issues related to PHP start and end tags. That is:

Copy code The code is as follows:

// Code...
?>

is usually the above form, in addition there is also an abbreviated form:

You can also use it

is abbreviated as:

This abbreviation is called Short Open Tag, which is enabled by default in PHP5.3 and always available in PHP5.4.
This shorthand can be very convenient for embedding PHP variables in HTML.

For pure PHP files (such as class implementation files), PHP officially recommends writing the start tag in the top space and omitting the end tag.
This ensures that the entire PHP file is PHP code without any output, otherwise you will encounter some trouble when setting the Header and Cookie after including the file [Note].

Note: Header and Cookie must be sent before any content is output.
Array abbreviation
This is a very convenient feature!

Copy code The code is as follows:

// Original array writing method
$arr = array("key" => "value", "key2" => "value2");
// Abbreviation
$arr = ["key" => "value", "key2" => "value2"];

Traits
The so-called traits are "components", which are a mechanism used to replace inheritance. Multiple inheritance is not possible in PHP, but a class can contain multiple Traits.

Copy code The code is as follows:

// Traits cannot be instantiated individually and can only be contained by classes
trait SayWorld
{
Public function sayHello()
{
echo 'World!';
}
}
class MyHelloWorld
{
//Include members from SayWorld
Use SayWorld;
}
$xxoo = new MyHelloWorld();
// sayHello() function is from SayWorld component
$xxoo->sayHello();
[code]

Traits also have many magical functions, such as containing multiple traits, resolving conflicts, modifying access permissions, setting aliases for functions, etc.
Traits can also include Traits. Due to limited space, we cannot give examples one by one. For details, please see the official website [Note].

Note: http://www.php.net/manual/zh/language.oop5.traits.php
Built-in web server
PHP has a built-in lightweight web server starting from 5.4, which does not support concurrency and is positioned for development and debugging environments.

It is indeed very convenient to use it in a development environment.

php -S localhost:8000

This will establish a web server in the current directory, which you can access through http://localhost:8000/.
Among them, localhost is the listening IP and 8000 is the listening port, which can be modified by yourself.

In many applications, URL rewriting is performed, so PHP provides a function to set routing scripts:

php -S localhost:8000 index.php

In this way, all requests will be handled by index.php.

You can also use XDebug for breakpoint debugging.
Details modified
PHP5.4 adds a new way to dynamically access static methods:
$func = "funcXXOO";
A::{$func}();

New feature for accessing class members during instantiation:

(new MyClass)->xxoo();

Added support for member access analysis of function return arrays (this writing method would report an error in previous versions):

print func()[0];

PHP5.5
(Since 2013)
yield
The yield keyword is used to return values ​​one by one when a function needs to return an iterator.

[code]
function number10()
{
for($i = 1; $i <= 10; $i += 1)
         yield $i;
}

The return value of this function is an array:
list() for foreach
Nested arrays can be parsed in foreach using list():

Copy code The code is as follows:

$array = [
[1, 2, 3],
[4, 5, 6],
];

foreach ($array as list($a, $b, $c))
echo "{$a} {$b} {$c}n";

Result:
1 2 3
4 5 6

Modification of details
The use of mysql functions is deprecated. It is recommended to use PDO or MySQLi, see the previous article.
Windows XP is no longer supported.

You can use MyClass::class to get the fully qualified name of a class (including namespace).

empty() supports expressions as parameters.

A finally block is added to the try-catch structure.
PHP5.6
Better constants
When defining constants, calculations using previously defined constants are allowed:

Copy code The code is as follows:

const A = 2;
const B = A + 1;

class C
{
const STR = "hello";
const STR2 = self::STR + ", world";
}

Allow constants as function parameter default values:
function func($arg = C::STR2)

Copy code for better variable function parameters
Used instead of func_get_args()

Copy code The code is as follows:

function add(...$args)
{
$result = 0;
foreach($args as $arg)
         $result += $arg;
Return $result;
}

Copy the code and expand the array into function parameters when calling the function:

Copy code The code is as follows:

$arr = [2, 3];
add(1, ...$arr);

//The result is 6

Namespace
Namespace supports constants and functions:

Copy code The code is as follows:

namespace NameSpace {
const FOO = 42;
function f() { echo __FUNCTION__."n"; }
}
namespace {
Use const NameSpaceFOO;
Use function NameSpacef;
echo FOO."n";
f();
}

php cannot log in, please help if php version 5225/5325/5425/5525 ​​cannot be used

If it is not configured, please try the phpstudy integration package to support one-click switching from php5.2 to 5.6. Give it a try. phpstudy as shown in the picture

How to install PHP533? What is the difference between PHP533 and PHP525? Why are there files in PHP533 (for example: "phpini

The latest Yinding version is 5.3.8. In fact, these versions have some improvements in security and functionality. The basic syntax has not changed. Install the latest version for the first time. Download it from php.net and install it directly. That’s it, close the web server before installation and it will automatically modify the configuration file for you

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/840646.htmlTechArticleDetailed explanation of the new features of PHP5.2 to 5.6, new features of php5.25.6 as of now (2014.2), PHP The latest stable version is PHP5.5, but almost half of the users are still using it and it is no longer maintained [Note...
Statement:
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