New features and new features in PHP5 _ PHP Tutorial

Source: Internet
Author: User
Tags spl mysql functions traits
New features and new features of PHP5. Because PHP's cool syntax, coupled with poor community atmosphere, many people are not interested in the new version and new features. This article will introduce PHP and later versions, because of the "hundreds of thousands of experts" of PHP, and the poor community atmosphere, many people are interested in the new version, new features are not of interest. This article will introduce new features added from PHP5.2 to PHP5.6.

Directory:
Before PHP5.2: autoload, PDO and MySQLi, type constraints
PHP5.2: JSON support
PHP5.3: deprecated functions, anonymous functions, new magic methods, namespaces, static binding later, Heredoc and Nowdoc, const, ternary operators, Phar
PHP5.4: Short Open Tag, abbreviated array format, Traits, built-in Web server, detailed modification
PHP5.5: yield, list () for foreach, details modification
PHP5.6: constant enhancement, variable function parameters, and namespace enhancement

I. PHP5.2 before (before 2006)
By the way, we will introduce the features that have appeared in PHP5.2 but are worth introducing.
Autoload
You may know the _ autoload () function. if this function is defined, the function will be called when an undefined class is used in the code, you can load the corresponding class implementation file in this function, such:

The code is as follows: function _ autoload ($ classname)
{
Require_once ("{$ classname}. php ")
}
However, this function is no longer recommended because only one such _ autoload () function is available in a project, because PHP does not allow repeated function names. But when you use some class libraries, it is inevitable that multiple autoload functions will be required, so spl_autoload_register () is replaced:
The code is as follows: spl_autoload_register (function ($ classname)
{
Require_once ("{$ classname}. php ")
});
Spl_autoload_register () registers a function to the autoload function list. When an undefined class is displayed, SPL [note] calls the registered autoload function one by one according to the registered inverted order, this means you can use spl_autoload_register () to register multiple autoload functions.
Note: SPL: Standard PHP Library, a Standard PHP Library, is designed to solve some classic problems (such as data structures ).

PDO and MySQLi
That is, PHP Data Object and PHP Data Object. this is a new PHP database access interface.
According to the traditional style, access to the MySQL database should be like this:

The code is as follows: // connect to the server and 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 the result
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 );


To enable the code to be unrelated to the database, that is, a piece of code is applicable to multiple databases (for example, the above code is only applicable to MySQL), PHP officially designed PDO.
In addition, PDO provides more functions, such:

1. object-oriented interfaces
2. SQL pre-compilation (prepare), placeholder syntax
3. higher execution efficiency. as an official recommendation, it has special performance optimizations.
4. supports most SQL databases. you do not need to change the code to change the database.

The above code is implemented using PDO as follows:

The code is as follows: // connect to the database
$ Conn = new PDO ("mysql: host = localhost; dbname = database", "user", "password ");

$ Query = $ conn-> prepare ("SELECT * FROM 'table' WHERE 'type' =: type ");
$ Query-> bindParam ("type", $ _ POST ['type']);

// Execute the query and print the result
Foreach ($ query-> execute () as $ row)
{
Foreach ($ row as $ k => $ v)
Print "{$ k }:{ $ v} \ n ";
} (Edit and organize the script School www.jbxue.com)


PDO is officially recommended for more common database access methods. if you do not have special requirements, you 'd better learn and use PDO.
However, if you need to use the advanced features specific to MySQL, you may need to try MySQL I, because in order to be able to use multiple databases at the same time, PDO does not include those unique functions of MySQL.

MySQLi is an enhanced MySQL interface that provides both process-oriented and object-oriented interfaces. it is also the MySQL driver currently recommended. the old C-style MySQL interface will be disabled by default in the future.

The usage of MySQLi does not have many new concepts compared with the above two sections of code. examples are not provided here. For details, refer to the PHP official website documentation [note].

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

Type constraints
The type constraints can be used to limit the type of parameters. However, this mechanism is not perfect. Currently, it is only applicable to classes, callable (executable type), and array (array). It is not applicable to string and int.

The code is as follows: // restrict the first parameter to MyClass, the second parameter to executable type, and the third parameter to array
Function MyFunction (MyClass $ a, callable $ B, array $ c)
{
//...
}

Including functions such as json_encode () and json_decode (). JSON is a commonly used data exchange format in the Web field and can be directly supported by JS. JSON is actually part of JS syntax.
JSON functions, which can convert the array structure in PHP to a JSON string:

The code is as follows: $ array = ["key" => "value", "array" => [1, 2, 3, 4];
$ Json = json_encode ($ array );
Echo "{$ json} \ n ";

Print_r ($ object );


Output:
The code is as follows: {"key": "value", "array": [1, 2, 4]}
StdClass Object
(
[Key] => value
[Array] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
)
It is worth noting that json_decode () returns an object rather than an array by default. to return an array, set the second parameter to true.

PHP5.3 (2009-2012)
PHP5.3 is a very large update, with a large number of new features added and some incompatible modifications made.
[PHP5.3 abandon function]: the following features are discarded. if enabled in the configuration file, PHP will issue a warning at runtime.

Register Globals
This is an option in php. ini (register_globals). after it is enabled, all form variables ($ _ GET and $ _ POST) are registered as global variables.
See the following example:

The code is as follows: if (isAuth ())
$ Authorized = true;
If ($ authorized)
Include ("page. php ");
When the code passes verification, set $ authorized to true, and then determine whether to display the page based on the value of $ authorized.
However, since $ authorized is not initialized to false in advance, when register_globals is enabled,/auth. php? Authorized = 1 to define the variable value and bypass authentication.
This feature is a historical issue. it is disabled by default in PHP4.2 and removed from PHP5.4.

Magic Quotes

Corresponding to the magic_quotes_gpc option in php. ini, this feature is also a historical issue and has been removed from PHP5.4.
This feature will escape all user input, which looks good. in the first chapter, we mentioned the need to escape user input.
However, PHP does not know which inputs will enter SQL, which will enter Shell, and which will be displayed as HTML. Therefore, this escape will often cause confusion.

Safe Mode
Many VM providers use Safe Mode to isolate multiple users, but Safe Mode has many problems. for example, some extensions do not implement permission control according to Safe Mode.
PHP officially recommends using the operating system mechanism for permission isolation to allow Web servers to run the PHP interpreter with different user permissions. for details, see the minimum permission principle in chapter 1.

[New and improved PHP5.3]

Anonymous functions
It is also called a closure (Closures). it is often used to temporarily create an unknown function for callback functions and other purposes.

The code is as follows: $ func = function ($ arg)
{
Print $ arg;
};

$ Func ("Hello World ");


The code above defines an anonymous function and assigns it to $ func.
You can see that the anonymous function still uses the function keyword, but the function name is omitted, directly the parameter list.
Then we call the anonymous function stored in $ func.
Anonymous functions can also use the use keyword to capture external variables:
The code is as follows: function arrayPlus ($ array, $ num)
{
Array_walk ($ array, function (& $ v) use ($ num ){
$ V + = $ num;
});
}
The code above defines an arrayPlus () function (this is not an anonymous function), which adds each item in an array ($ array) with a specified number ($ num ).
In the implementation of arrayPlus (), we use the array_walk () function, which executes a callback function for each item of an array, that is, the anonymous function we define.
After the parameter list of the anonymous function, we use the use keyword to capture $ num outside the anonymous function into the function to know how much it should be added.

Magic method: __invoke (), _ callStatic ()
PHP's object-oriented system provides several "magic methods" for implementing "overload" similar to 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:

The code is as follows: class
{
Public function _ invoke ($ str)
{
Print "A ::__ invoke (): {$ str }";
}
}

$ A = new;
$ A ("Hello World ");


The output is undoubtedly:
The code is as follows: A :__ invoke (): Hello World
_ CallStatic () is called when a non-existent static method is called.


Namespace
The PHP namespace has a syntax that never comes before:

The code is as follows: // The namespace separator is a backslash. the declaration statement must be in the first line of the file.
// The namespace can contain any code, but only ** classes, functions, and constants ** are affected by the namespace.
Namespace XXOO \ Test;

// The Complete qualified name of this class is \ XXOO \ Test \ A. The first backslash indicates the global namespace.
Class {}

// You can also define the second namespace in the file. the subsequent code will be located in \ Other \ Test2.
Namespace Other \ Test2;

// Instantiate objects from other namespaces:
$ A = new \ XXOO \ Test \;
Class B {}

// You can also use curly brackets to define the third namespace
Namespace Other {
// Instantiate the object from the sub-namespace:
$ B = new Test2 \ B;

// Import the name from another namespace and rename it,
// Note that only classes can be imported and cannot be used for functions or constants.
Use \ XXOO \ Test \ A as ClassA
}


For more information about the namespace syntax, see [note] on the official website.
Namespaces are often used together 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 full qualified name of this class will be passed to the autoload function. the autoload function will use the namespace separator (backslash) in the class name) replace it with a slash and contain the corresponding file.
In this way, class definition files can be stored hierarchically and automatically loaded as needed.
Note: http://www.php.net/manual/zh/language.namespaces.php

Static binding later
PHP's OPP mechanism provides inheritance and functions similar to virtual functions, such as the following code:

The code is as follows: class
{
Public function callFuncXXOO ()
{
Print $ this-> funcXXOO ();
}

Public function funcXXOO ()
{
Return "A: funcXXOO ()";
}
}

Class B extends
{
Public function funcXXOO ()
{
Return "B: funcXXOO ";
}
}

$ B = new B;
$ B-> callFuncXXOO ();


The output is:
The code is as follows: B: funcXXOO
We can see that when $ this-> funcXXOO () is used in A, the "virtual function" mechanism is embodied. actually, B: funcXXOO () is called ().
However, if you change all functions to static functions:
The code is as follows: class
{
Static public function callFuncXXOO ()
{
Print self: funcXXOO ();
}

Static public function funcXXOO ()
{
Return "A: funcXXOO ()";
}
}

Class B extends
{
Static public function funcXXOO ()
{
Return "B: funcXXOO ";
}
}

$ B = new B;
$ B-> callFuncXXOO ();


The situation is not so optimistic. the output is:
The code is as follows: A: funcXXOO ()
This is because the semantics of self is "current class", so PHP5.3 gives a new function to the static keyword: static binding in the later stage:
The code is as follows: class
{
Static public function callFuncXXOO ()
{
Print static: funcXXOO ();
}

//...
}

//...


The output will be as expected:
The code is as follows: B: funcXXOO

Heredoc and Nowdoc

PHP5.3 makes some improvements to Heredoc and Nowdoc, which are used to embed large strings in PHP code.
Heredoc acts like a double quotation mark string:

The code is as follows: $ name = "MyName ";
Echo <TEXT
My name is "{$ name }".
TEXT;
Heredoc starts with three left angle brackets and ends with an identifier (TEXT) until the end of an identifier (which cannot be indented) with the same ceiling.
Just like a double quotation mark string, variables can be embedded.

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

The code is as follows: var_dump (< Hello World
EOD
);

Class
{
Const xx = <EOD
Hello World
EOD;

Public $ oo = <EOD
Hello World
EOD;
}


Nowdoc acts like a single quotes string and cannot embed variables in it. The only difference between Nowdoc and Heredoc is that the identifiers after the three left angle brackets must be enclosed in single quotes:
The code is as follows: $ name = "MyName ";
Echo <'text'
My name is "{$ name }".
TEXT;
Output:
The code is as follows: My name is "{$ name }".

Use const to define constants

From PHP5.3, you can use const to define constants in global namespaces and classes.
Old style:

The code is as follows: define ("XOOO", "Value ");
New style:
Const XXOO = "Value ";
The const format is only applicable to constants and does not apply to expressions that can be evaluated at runtime:
The code is as follows: // correct
Const XXOO = 1234;
// Error
Const XXOO = 2*617;

Ternary operators
Old style:

The code is as follows: echo $? $ A: "No Value ";
Can be abbreviated:
The code is as follows: echo $? : "No Value ";
That is, if the second part of the ternary operator is omitted, the first part is replaced by default.

Phar

Phar is PHP Archive. it was originally a library in Pear. later, it was rewritten as a C extension in PHP5.3 and built into PHP.
Phar is used to package multiple. php scripts (you can also package other files) into a. phar compressed file (usually in ZIP format ).
The purpose is to imitate Java. jar. no, the purpose is to make it easier to publish PHP applications. It also provides functions such as digital signature verification.
The. phar file can be interpreted and executed by the php engine like the. PHP file. you can also write such code to include (require). phar code:

The code is as follows: require ("xxoo. phar ");
Require ("phar: // xxoo. phar/xo/ox. php ");
For more information, see [note] on the official website.
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 PHP start and end labels. That is:

The code is as follows: // Code...
?>
This is usually the form above. In addition, there is also a shorthand form:
The code is as follows:
You can also
The code is as follows:
Abbreviated:
The code is as follows:
This Short form is called the Short Open Tag, which is enabled by default in PHP5.3 and always available in php5.4.
It is very convenient to embed PHP variables in HTML using this short form.

For pure PHP files (such as class implementation files), PHP officially recommends that you write the start mark in the top cell and omit the end mark.
This ensures that the entire PHP file is PHP code without any output. otherwise, when you include the file and set the Header and Cookie, you may encounter some problems. [note]

Note: the Header and Cookie must be sent before any content is output.

Array abbreviations
This is a very convenient feature!

The code is as follows: // write the original array
$ Arr = array ("key" => "value", "key2" => "value2 ");
// Abbreviated form
$ Arr = ["key" => "value", "key2" => "value2"];

Traits
Traits is a "component" and a mechanism used to replace inheritance. PHP cannot carry out multiple inheritance, but a class can contain multiple Traits.

The code is as follows: // Traits cannot be instantiated separately and can only be contained by classes.
Trait SayWorld
{
Public function sayHello ()
{
Echo 'World! ';
}
}

Class MyHelloWorld
{
// Include the members in SayWorld
Use SayWorld;
}

$ Xxoo = new MyHelloWorld ();
// The sayHello () function comes from the SayWorld component.
$ Xxoo-> sayHello ();


Traits also has many magical functions, such as including multiple Traits, resolving conflicts, modifying access permissions, and setting aliases for functions.
Traits can also contain Traits. For more information, see [note].
Note: http://www.php.net/manual/zh/language.oop5.traits.php

Built-in Web server
PHP has built a lightweight Web server from 5.4 and does not support concurrency. it is positioned for development and debugging environments.
It is indeed very convenient to use in the development environment.

The code is as follows: php-S localhost: 8000
In this way, a Web server is created in the current directory, which can be accessed through http: // localhost: 8000.
Localhost is the ip address of the listener, and 8000 is the listening port. you can modify it on your own.

In many applications, URL rewriting is required. Therefore, PHP provides a routing script setting function:

The code is as follows: php-S localhost: 8000 index. php
In this way, all requests will be processed by index. php.
You can also use XDebug for breakpoint debugging.

Details modification
PHP5.4 adds a method for dynamically accessing static methods:

The code is as follows: $ func = "funcXXOO ";
A: {$ func }();
New features of the feature class members during instantiation:
The code is as follows: (new MyClass)-> xxoo ();
Added support for accessing and parsing the members of the array returned by the function (this method will report an error in the previous version ):
The code is as follows: print func () [0];

PHP5.5 (from 2013)

Yield
The yield keyword is used to return values one by one when the function needs to return an iterator.

The code is as follows: function number10 ()
{
For ($ I = 1; $ I <= 10; $ I + = 1)
Yield $ I;
}
The return value of this function is an array:
The code is as follows: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List () for foreach
You can use list () to parse nested arrays in foreach:
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:
The code is as follows: 1 2 3
4 5 6
Details modification
Mysql functions are not recommended. PDO or MySQLi is recommended. See the previous article.
Windows XP is no longer supported.
Use MyClass: class to get the full qualified name (including the namespace) of a class ).
Empty () supports expressions as parameters.
The try-catch structure adds finally blocks.

PHP5.6

Better constants
When defining constants, you can use the previously defined constants for calculation:

The code is as follows: const A = 2;
Const B = A + 1;

Class C
{
Const STR = "hello ";
Const STR2 = self: STR + ", world ";
}


Constant can be used as the default value of function parameters:
The code is as follows: function func ($ arg = C: STR2)

Better variable function parameters
Used to replace func_get_args ()

The code is as follows: function add (... $ args)
{
$ Result = 0;
Foreach ($ args as $ arg)
$ Result + = $ arg;
Return $ result;
}
You can expand the array as a function parameter when calling a function:
The code is as follows: $ arr = [2, 3];
Add (1,... $ arr );
// The result is 6.
Namespace
Namespaces support constants and functions:
The code is 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 ();
}

In addition to poor community atmosphere, many people are not interested in the new version and new features. This article will introduce the content added from PHP5.2 to PHP5.6...

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.