Home > Article > Backend Development > Detailed explanation of new features from PHP5.2 to 5.6, new features in php5.25.6_PHP Tutorial
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:
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:
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:
//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:
//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.
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:
$object = json_decode($json);
print_r($object);
Output:
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:
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.
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:
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:
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:
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:
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:
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:
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:
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 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:
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:
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:
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:
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:
is usually the above form, in addition there is also an abbreviated form:
/* Code... */ ?>
You can also use it
is abbreviated as:
= $xxoo;?>
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!
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.
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():
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:
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 the code and expand the array into function parameters when calling the function:
//The result is 6
Namespace
Namespace supports constants and functions:
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
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