PHP5 new features and features for each version _php tutorial

Source: Internet
Author: User
Tags autoload finally block spl traits least privilege
This article directory:
PHP5.2 before: AutoLoad, PDO, and mysqli, type constraints
Php5.2:json Support
PHP5.3: Deprecated features, anonymous functions, New magic methods, namespaces, late static bindings, Heredoc and Nowdoc, const, ternary operators, Phar
Php5.4:short Open Tag, array shorthand form, Traits, built-in Web server, detail modified
Php5.5:yield, List () for foreach, detail modification
PHP5.6: constant enhancement, variable function parameters, namespace enhancement

PHP5.2 before (2006)
by the way, the features that PHP5.2 has appeared but worth introducing.
Everyone probably knows the __autoload () function, and if the function is defined, the function is called when an undefined class is used in the code. You can load the corresponding class implementation file in the function, such as:
copy code code as follows: function __autoload ($classname)
Require_once ("{$classname}.php")
But it has not been recommended because only one of these can be used in a project. _autoload () function, because PHP does not allow the names of functions. But when you use some class libraries, there will inevitably be multiple autoload functions, so Spl_autoload_register () instead:
copy code code is as follows: Spl_autoload_register (function ($classname)
Require_once (" {$ classname}.php ")
Spl_autoload_register () registers a function in the list of AutoLoad functions, and when an undefined class is present, SPL [note] invokes the registered AutoLoad function one at a time in reverse order, which means that you can use Spl_ Autoload_register () registers multiple autoload functions.
Note: Spl:standard PHP library, standard PHP libraries, is designed to solve some classic problems (such as data structures).

PDO and Mysqli
That is, PHP data object, PHP, which is the new database access interface of PHP.
In the traditional style, access to the MySQL database should look like this:
Copy the code as follows://Connect to server, select 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, close the connection
Mysql_free_result ($result);
Mysql_close ($conn);
To be able to make the code implement database-independent, that is, a piece of code for a variety of databases (for example, the above code only for MySQL), PHP officially designed PDO.
In addition to this, PDO offers more features, such as:

1. Object-oriented style interface
2.SQL Pre-compilation (prepare), placeholder syntax
3. Higher execution efficiency, as an official recommendation, with special performance optimizations
4. Support Most SQL database, replace the database without changing the code

The above code will be implemented in PDO:
Copy the Code Code as follows://Connect to Database
$conn = new PDO ("Mysql:host=localhost;dbname=database", "User", "password");

Precompiled SQL, binding parameters
$query = $conn->prepare ("SELECT * from ' table ' WHERE ' type ' =: type ');
$query->bindparam ("type", $_post[' type ');

Execute a query and print the results
foreach ($query->execute () as $row)
foreach ($row as $k = $v)
Print "{$k}: {$v}\n";
PDO is an officially recommended, more generic way to access your database, and if you don't have special needs, then you'd better learn and use PDO.
But if you need to use the advanced features that are unique to MySQL, you might want to try Mysqli, because PDO does not include features that are unique to MySQL in order to be able to use it on multiple databases at the same time.

MYSQLI is an enhanced interface for MySQL, providing both process-oriented and object-oriented interfaces, as well as the currently recommended MySQL driver, and the old C-style MySQL interface will be turned off by default in the future.
There are not many new concepts in the usage of mysqli compared to the above two pieces of code, which are no longer presented here, and can be found in the PHP official website documentation [note].


Type constraints
Type constraints allow you to limit the type of a parameter, but this mechanism is imperfect, and currently applies only to classes and callable (executable types), and to Array (arrays), not to string and int.
Copy the Code Code as follows://Limit the first parameter to MyClass, the second argument 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 popular data interchange format in the WEB domain, can be directly supported by JS, JSON is actually part of the JS syntax.
JSON series functions, you can convert the structure of an array in PHP to a JSON string:
Copy the code as follows: $array = ["Key" = "value", "array" = [1, 2, 3, 4]];
$json = Json_encode ($array);
echo "{$json}\n";

$object = Json_decode ($json);
Print_r ($object);
Copy the code as follows: {"key": "Value", "array": [1,2,3,4]}
StdClass Object
[Key] = value
[Array] + = array
[0] = 1
[1] = 2
[2] = 3
[3] = 4
It is important to note that Json_decode () returns an object instead of an array by default, and if it is necessary to return an array, set the second argument to true.

PHP5.3 (2009-2012)
PHP5.3 is a very big update, adding a lot of new features, but also made some non-compatible changes.
"PHP5.3 deprecated Features": The following features are deprecated and, if enabled in the configuration file, PHP warns you at runtime.

Register Globals
This is an option in php.ini (register_globals), which registers all form variables ($_get and $_post) as global variables when turned on.
Look at the following example:
Copy the Code code as follows: if (Isauth ())
$authorized = true;
if ($authorized)
Include ("page.php");
This code sets the $authorized to True when it passes validation. The page is then determined based on the value of the $authorized.
However, since the $authorized is not initialized to false beforehand, when Register_globals is opened, it is possible to access/auth.php?authorized=1 to define the value of the variable, bypassing the authentication.
This feature is a legacy issue, which is closed by default in PHP4.2 and removed in PHP5.4.

Magic Quotes

corresponding to the option MAGIC_QUOTES_GPC in php.ini, this feature is also a legacy issue that has been removed in PHP5.4.
This feature escapes all user input, which looks good, and in the first chapter we talked about escaping user input.
However, PHP does not know which inputs will go into SQL, which input will go into the Shell, and which inputs will be displayed as HTML, so this escape can cause confusion in many cases.

Safe Mode
Many virtual hosting providers use Safe mode to isolate multiple users, but safe mode has many problems, such as some extensions that do not follow Safe mode for permission control.
PHP officially recommends using the operating system mechanism for permission isolation, allowing the Web server to run the PHP interpreter with different user rights, see the principle of least privilege in Chapter I.

"New and improved PHP5.3"

anonymous functions
Also known as closures (Closures), is often used to temporarily create a nameless function for use in callback functions.
Copy the Code code as follows: $func = function ($arg)
Print $arg;

$func ("Hello World");
The code above defines an anonymous function and assigns a value to the $func.
You can see that defining an anonymous function still uses the function keyword, except that it omits the name and is directly a parameter list.
Then we call the anonymous function stored in the $func.
Anonymous functions can also capture external variables with the USE keyword:
Copy the Code code as follows: function Arrayplus ($array, $num)
Array_walk ($array, function (& $v) use ($num) {
$v + = $num;
The above code defines a arrayplus () function (which is not an anonymous function), which adds each item in an array ($array) with a specified number ($num).
In the implementation of Arrayplus (), we used the Array_walk () function, which executes a callback function for each item of an array, which is the anonymous function we define.
After the argument list of the anonymous function, we use the Using keyword to snap the $num outside of the anonymous function into the function to know exactly how much to add.

Magic method: __invoke (), __callstatic ()
In the object-oriented architecture of PHP, a number of "magic methods" are provided to implement "overloads" similar to those in other languages, such as triggering a magic method when accessing a nonexistent property or method.
With the addition of anonymous functions, PHP introduces a new Magic Method __invoke ().
The Magic method is called when an object is called as a function:
Copy the Code code as follows: Class A
Public Function __invoke ($STR)
Print "A::__invoke (): {$str}";

$a = new A;
$a ("Hello world");
The output is undoubtedly:
Copy the Code code as follows: A::__invoke (): Hello World
__callstatic () is called when a static method that does not exist is called.

Name space
PHP's namespace has the most unprecedented egg-aching syntax:
Copy the code as follows: //The delimiter for the namespace is a backslash, and the declaration statement must be on the first line of the file.
Namespaces can contain arbitrary code, but only * * classes, Functions, constants * * are affected by the namespace.
namespace Xxoo\test;

The fully qualified name of the class is \xxoo\test\a, where the first backslash represents a global namespace.
Class a{}

You can also define a second namespace in an already file, and the next code will be in \other\test2.
namespace Other\test2;

Instantiate an object from another namespace:
$a = new \xxoo\test\a;
Class b{}

You can also define a third namespace with curly braces
namespace Other {
Instantiate an object from a child namespace:
$b = new test2\b;

Import names from other namespaces, rename them,
Note You can import only classes and cannot be used for functions and constants.
Use \xxoo\test\a as ClassA
For more information about namespaces, see the official website [note].
Namespaces are often used in conjunction with AutoLoad to automatically load class implementation files:

Spl_autoload_register (
function ($class) {
Spl_autoload (str_replace ("\ \", "/", $class));
When you instantiate a class \xxoo\test\a, the fully qualified name of the class is passed to the AutoLoad function, and the AutoLoad function replaces the namespace delimiter (backslash) in the class name with a slash and contains the corresponding file.
This enables class definition file classification to be stored and loaded automatically on demand.

Late static binding
PHP's OPP mechanism, with inheritance and similar virtual functions, such as the following code:
Copy the Code code 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:
Copy the Code code as follows: B::funcxxoo
As you can see, when you use $this->funcxxoo () in a, the mechanism that embodies the "virtual function" is actually called B::funcxxoo ().
However, if all functions are changed to static functions:
Copy the Code code 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:
Copy the Code code as follows: A::funcxxoo ()
This is because the semantics of self are inherently "current class", so PHP5.3 gives a new feature to the static keyword: late static binding:
Copy the Code code as follows: Class A
static public Function Callfuncxxoo ()
Print Static::funcxxoo ();

// ...

// ...
This will output as expected:
Copy the Code code as follows: B::funcxxoo

Heredoc and Nowdoc

PHP5.3 has made some improvements to Heredoc and Nowdoc, all of which are used to embed large strings in PHP code.
The behavior of Heredoc is similar to a double-quote string:
Copy the Code code as follows: $name = "MyName";
Echo <<< TEXT
My name is "{$name}".
Heredoc begins with three left angle brackets followed by an identifier (TEXT) until an identifier of the same shelf (not indented) ends.
Just like a double-quoted string, where you can embed a variable.

Heredoc can also be used for function parameters, as well as for class member initialization:
Copy the Code code as follows: Var_dump (<<<>
Hello World

Class A
Const XX = <<< EOD
Hello World

Public $oo = <<< EOD
Hello World
Nowdoc behaves like a single-quote string, where a variable cannot be embedded, and Heredoc the only difference is that the identifiers after three left angle brackets are enclosed in single quotes:
Copy the Code code as follows: $name = "MyName";
echo <<< ' TEXT '
My name is "{$name}".
Copy the code as follows: My name is "{$name}".

Defining constants with Const

PHP5.3 also supports the use of Const definition constants in global namespaces and classes.
Old Style:
Copy the Code code as follows: Define ("Xooo", "Value");
New style:
Const XXOO = "Value";
The const form applies only to constants, not to expressions that can be evaluated at run time:
Copy the Code Code as follows://correct
Const XXOO = 1234;
Const XXOO = 2 * 617;

Abbreviated form of ternary operator
Old Style:
Copy the Code code as follows: Echo $a? $a: "No Value";
Can be written as:
Copy the code as follows: Echo $a?: "No Value";
That is, if the second part of the ternary operator is omitted, the first part is replaced by default.


Phar, PHP Archive, was originally just a library in pear, and later was rewritten as a C extension in PHP5.3 and built into PHP.
Phar is used to package multiple. PHP scripts (or to package other files) into a. Phar Compressed file (usually in zip format).
The goal is to mimic Java's. jar, which is wrong, to make it easier to publish PHP applications. It also provides features such as digital signature verification.
The. Phar file can be interpreted by the PHP engine as if it were a. php file, and you can also write code to contain (require) the code in Phar:
Copy the Code code as follows: Require ("Xxoo.phar");
Require ("phar://xxoo.phar/xo/ox.php");
For more information, please see the official website [note].

PHP5.4 (2012-2013)

Short Open Tag
The short Open Tag is always available from PHP5.4.
Focus on the issue of PHP start and end tags here. That
Copy the Code : //code ...
This is usually the form above, in addition to a shorthand form:
Copy the Code code as follows:
can also put
Copy the Code code as follows:
Jane writes:
Copy the Code code as follows:
This shorthand form, known as the short open Tag, is turned on by default at PHP5.3 and is always available at PHP5.4.
It is very convenient to embed PHP variables in HTML in this shorthand form.

For pure PHP files (such as class implementation files), PHP officially recommends shelf write the start tag, while omitting the end tag.
This ensures that the entire PHP file is PHP code, without any output, or you will encounter some trouble setting the Header and Cookie when you include the file [note].

Note: Headers and cookies must be sent before any content is output.

Array Shorthand form
This is a very handy feature!
Copy the Code Code as follows://original array notation
$arr = Array ("Key" = "value", "key2" = "value2");
Shorthand form
$arr = ["Key" = "value", "key2" = "value2"];

The so-called traits is the "component", which is a mechanism to replace inheritance. Multiple inheritance is not possible in PHP, but a class can contain multiple traits.
The copy Code code is as follows://traits cannot be instantiated by itself, only by class
Trait Sayworld
Public Function SayHello ()
Echo ' world! ';

Class Myhelloworld
Include the members in the Sayworld
Use Sayworld;

$xxoo = new Myhelloworld ();
The SayHello () function is from the Sayworld component.
$xxoo->sayhello ();
Traits also has many magical features, such as including multiple traits, resolving conflicts, modifying access rights, setting aliases for functions, and so on.
The traits can also contain traits. Limited space is not an example, please refer to the official website [note].

Built-in Web server
PHP starts with a 5.4 built-in lightweight Web server, does not support concurrency, and is used for development and debugging environments.
It is really handy to use it in the development environment.
Copy the Code code as follows: Php-s localhost:8000
This creates a Web server in the current directory that you can access through http://localhost:8000/.
Where localhost is the listening ip,8000 is the listening port, can be modified by itself.

In many applications, url rewriting is done, so PHP provides a function to set up a routing script:
Copy the Code code as follows: Php-s localhost:8000 index.php
In this way, all requests are handled by index.php.
You can also use XDebug to debug breakpoints.

Details modification
PHP5.4 adds a way to dynamically access static methods:
Copy the Code code as follows: $func = "Funcxxoo";
a::{$func} ();
New features that access class members when instantiated:
Copy the Code Code as follows: (New MyClass)->xxoo ();
Added support for member access parsing of function return arrays (this is an error in previous versions):
Copy the Code code as follows: Print func () [0];

PHP5.5 (from 2013)

The yield keyword is used to return values one at a time when the function needs to return an iterator.
Copy the Code code as follows: function Number10 ()
for ($i = 1; $i <=; $i + = 1)
Yield $i;
The return value of the function is an array:
Copy the Code code as follows: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List () for foreach
Nested arrays can be parsed in foreach using List ():
Copy the Code code as follows: $array = [
[1, 2, 3],
[4, 5, 6],

foreach ($array as list ($a, $b, $c))
echo "{$a} {$b} {$c}\n";
Copy the Code Code as follows: 1 2 3
4 5 6
Details modification
It is not recommended to use the MySQL function, PDO or mysqli is recommended, see the previous article.
Windows XP is no longer supported.
You can use Myclass::class to fetch the fully qualified name of a class, including the namespace.
Empty () supports expressions as arguments.
The TRY-CATCH structure adds a finally block.


A better constant
Defining constants allows calculations using constants defined previously:
Copy the Code code as follows: const A = 2;
Const B = A + 1;

Class C
Const STR = "Hello";
Const STR2 = Self::str + ", world";
Allow constants as default values for function parameters:
Copy the Code code as follows: function func ($arg = c::str2)

Better variable function parameters
Used instead of Func_get_args ()
Copy the Code code as follows: Function Add (... $args)
$result = 0;
foreach ($args as $arg)
$result + = $arg;
return $result;
You can also expand the array to function parameters when calling the function:
Copy the Code code as follows: $arr = [2, 3];
Add (1, ... $arr);
Result is 6
Name space
Namespaces support constants and functions:
Copy the Code code as follows: namespace Name\space {
Const FOO = 42;
function f () {echo __function__. \ n "; }

namespace {
Use const Name\space\foo;
Use function name\space\f;

echo FOO. " \ n ";
f ();
} true techarticle This document: PHP5.2 previously: AutoLoad, PDO and mysqli, type constraints Php5.2:json support PHP5.3: Deprecated features, anonymous functions, New magic methods, namespaces, post-static ...

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