PHP5 the new features and new features of each version _php skills

Source: Internet
Author: User
Tags autoload class definition finally block spl mysql in first row traits least privilege

This article directory:
PHP5.2 before: AutoLoad, PDO and mysqli, type constraints
Php5.2:json Support
PHP5.3: Deprecated functions, 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, details modification
Php5.5:yield, List () for foreach, detail modification
PHP5.6: Constant enhancements, variable function parameters, namespace enhancements

First, PHP5.2 before (2006 ago)
By the way, the features that PHP5.2 has appeared but are worth introducing.
AutoLoad
You probably all know the __autoload () function, and if you define the function, the function is invoked when you use an undefined class in your code, and 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")
}

This function is not recommended, however, because only one such __autoload () function can be used in a project because PHP does not allow duplicate functions. But when you use some class libraries, there will inevitably be more than one autoload function needed, so Spl_autoload_register () instead:
Copy Code code 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 occurs, SPL [note] invokes the registered AutoLoad function one at a time, meaning that you can use the Spl_ Autoload_register () registers multiple autoload functions.
Note: Spl:standard PHP library, standard PHP libraries, is designed to solve some of the classic problems (such as data structures).

PDO and Mysqli
PHP data Object, PHP, this is the new database access interface PHP.
In traditional style, accessing the MySQL database should look like this:

Copy Code 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);


In order for the code to implement the database independent, that is, a piece of code at the same time for a variety of databases (such as the above code is only applicable to MySQL), PHP official design PDO.
In addition to this, PDO also offers more features, such as:

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

The above code implemented with PDO will be like this:

Copy Code code as follows:
Connecting to a database
$conn = new PDO ("Mysql:host=localhost;dbname=database", "User", "password");

Pre-compiling SQL, binding 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 an officially recommended, more general way to access a 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 will not include features that are unique to MySQL in order to be able to use it on a variety of databases at the same time.

Mysqli is MySQL's enhanced interface, while providing a process-oriented and object-oriented interface, is also currently recommended MySQL driver, the old C-style MySQL interface will be closed by default in the future.
Mysqli usage and the above two pieces of code, there is not much new concept, here no longer to show examples, you can see the PHP official website document [note].

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

Type constraint
Type constraints allow you to restrict the type of a parameter, but this mechanism is not perfect, and is currently applicable only to classes and callable (executable types) and array (array) and not to string and int.

Copy Code code as follows:
Restricts the first argument to MyClass, the second parameter is an executable type, and the third argument is an 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 common in the Web field of data Interchange format, can be directly supported by JS, JSON is actually part of the JS syntax.
JSON series function that converts an array structure in PHP to a JSON string:

Copy Code 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);


Output:
Copy Code 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's worth noting that Json_decode () returns an object instead of an array by default, and if you need to return an array, you need to set the second argument to true.

PHP5.3 (2009-2012)
PHP5.3 is a very big update, adding a lot of new features and making some backward-compatible changes.
"PHP5.3 deprecated Features": The following features are deprecated, and if enabled in a configuration file, PHP warns at run time.

Register Globals
This is an option in php.ini (register_globals), which registers all form variables ($_get and $_post) as global variables when it is turned on.
Look at the following example:

Copy Code code as follows:
if (Isauth ())
$authorized = true;
if ($authorized)
Include ("page.php");

This code sets the $authorized to True when the validation is passed. Then decide whether to display the page based on the value of the $authorized.
However, since the $authorized is not initialized to false in advance, when Register_globals is open, it is possible to access/auth.php?authorized=1 to define the variable value, bypassing authentication.
This feature is a legacy issue that is closed by default in PHP4.2 and removed in PHP5.4.

Magic Quotes

corresponding to the options in PHP.ini MAGIC_QUOTES_GPC, this feature is also a legacy of history and has been removed from the PHP5.4.
This feature will escape all user input, which looks good, in the first chapter we mentioned the escape of user input.
But PHP doesn't know which input goes into SQL, which input goes into the Shell, and which input is displayed as HTML, so many times this escape can cause confusion.

Safe Mode
Many virtual host 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 official recommended to use the operating system mechanism for permission isolation, so that the Web server with different user rights to run the PHP interpreter, see the first chapter of the principle of least privilege.

"New and improved PHP5.3"

anonymous functions
Also called closure (Closures), it is often used to temporarily create a nameless function for use with callback functions.

Copy Code code as follows:
$func = function ($arg)
{
Print $arg;
};

$func ("Hello World");


The above code 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 is omitted from its name and is directly a parameter list.
Then we call the anonymous function stored by the $func.
Anonymous functions can also catch external variables with the USE keyword:
Copy Code code as follows:
function Arrayplus ($array, $num)
{
Array_walk ($array, function (& $v) use ($num) {
$v + + $num;
});
}

The code above defines a arrayplus () function (which is not an anonymous function) that adds each item in an array ($array), plus 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, the anonymous function we define.
After the list of parameters for the anonymous function, we capture the $num outside the anonymous function with the USE keyword to the function to see how much should be added.

Magic method: __invoke (), __callstatic ()
In the object-oriented system of PHP, several "magic methods" are provided to implement "overloads" in other languages, such as triggering a magic method when accessing nonexistent properties and methods.
With the addition of anonymous functions, PHP introduced a new Magic Method __invoke ().
The Magic method is invoked when an object is called as a function:

Copy 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 Code code as follows:
A::__invoke (): Hello World

__callstatic () is invoked when a static method that does not exist is invoked.


Name space
The namespace of PHP has an unparalleled, unprecedented syntax for egg aches:

Copy Code code as follows:
<?php
The delimiter for the namespace is a backslash, which must be in the first row of the file.
Namespaces can contain arbitrary code, but only * * classes, Functions, constants * are affected by namespaces.
namespace Xxoo\test;

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

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

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

You can also use curly braces to define a third namespace
namespace Other {
To instantiate an object from a child namespace:
$b = new test2\b;

Import names from other namespaces, and rename them,
Note You can only import classes, not 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 separator (backslash) in the class name with a slash and contains the corresponding file.
This enables the class definition file to be stored hierarchically and automatically loaded on demand.
Note: http://www.php.net/manual/zh/language.namespaces.php

Late static binding
The OPP mechanism of PHP has inheritance and functions like virtual functions, such as the following code:

Copy 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 Code code as follows:
B::funcxxoo

As you can see, when you use $this->funcxxoo () in a, you embody the mechanism of "virtual function", which is actually called B::funcxxoo ().
However, if all functions are changed to static functions:
Copy 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 Code code as follows:
A::funcxxoo ()

This is because the semantics of self are inherently "current classes," So PHP5.3 gives the static keyword a new feature: late static binding:
Copy Code code as follows:
Class A
{
static public Function Callfuncxxoo ()
{
Print Static::funcxxoo ();
}

// ...
}

// ...


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

Heredoc and Nowdoc

PHP5.3 has made some improvements to Heredoc and Nowdoc, both of which are used to embed large segments of strings in PHP code.
The behavior of Heredoc is similar to a double quote string:

Copy Code code as follows:
$name = "MyName";
Echo <<< TEXT
The My name is ' {$name} '.
TEXT;

The Heredoc begins with three left angle brackets followed by an identifier (TEXT) until the same below identifier (not indented) ends.
Just like a double quote string, you can embed a variable.

Heredoc can also be used for function arguments, as well as class member initialization:

Copy Code code as follows:
Var_dump (<<<eod
Hello World
EOD
);

Class A
{
Const XX = <<< EOD
Hello World
EOD;

Public $oo = <<< EOD
Hello World
EOD;
}


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

Output:
Copy Code code as follows:
The My name is ' {$name} '.

Define constants with const

PHP5.3 also supports the use of Const definition constants in global namespaces and classes.
Old Style:

Copy 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 Code code as follows:
That's right
Const XXOO = 1234;
Error
Const XXOO = 2 * 617;

Ternary operator Shorthand form
Old Style:

Copy Code code as follows:
echo $a? $a: "No Value";

Can be written by Jane:
Copy Code 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

Phar, PHP Archive, was originally a library in pear, and later PHP5.3 was rewritten as a C extension 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 emulate Java. Jar, no, to make it easier to publish PHP applications. At the same time also provides a digital signature verification and other functions.
The. Phar file can be interpreted and executed by the PHP engine as a. php file, and you can also write code that contains (require). Code in Phar:

Copy Code code as follows:
Require ("Xxoo.phar");
Require ("phar://xxoo.phar/xo/ox.php");

For more information please refer to the official website [note].
Note: http://www.php.net/manual/zh/phar.using.intro.php

PHP5.4 (2012-2013)

Short Open Tag
The short Open Tag is always available from PHP5.4.
Here to talk about the beginning and end of PHP tag issues. That

Copy Code code as follows:
<?php
Code ...
?>

This is usually the form above, but there is also a shorthand form:
Copy Code code as follows:
? /* Code ... * *?>

can also put
Copy Code code as follows:
<?php echo $xxoo;? >

Jane writes:
Copy Code code as follows:
<?= $xxoo;? >

This shorthand form, called the short open Tag, is turned on by default at PHP5.3 and is always available at PHP5.4.
It is convenient to embed PHP variables in HTML using this shorthand form.

For pure PHP files (such as class implementation files), PHP is officially recommended to below write the start tag and omit the end tag.
This will ensure that the entire PHP file is PHP code, there is no output, otherwise when you include the file, the Header and Cookie set up some trouble [note].

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

Array Shorthand form
This is a very convenient feature!

Copy Code code as follows:
The original array notation
$arr = Array ("Key" => "value", "Key2" => "value2");
Abbreviated form
$arr = ["Key" => "value", "Key2" => "value2"];

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

Copy Code code as follows:
Traits cannot be instantiated separately and can only be contained by a class
Trait Sayworld
{
Public Function SayHello ()
{
Echo ' world! ';
}
}

Class Myhelloworld
{
Include members in the Sayworld
Use Sayworld;
}

$xxoo = new Myhelloworld ();
The SayHello () function is derived from the Sayworld widget
$xxoo->sayhello ();


Traits also has a lot of 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 can not be one by one example, details see official website [note].
Note: http://www.php.net/manual/zh/language.oop5.traits.php

Built-in WEB server
PHP has a lightweight web server built from 5.4 and does not support concurrency, and positioning is used for development and debugging environments.
It's really handy to use in a development environment.

Copy Code code as follows:
Php-s localhost:8000

This creates a Web server in the current directory that you can access via http://localhost:8000/.
Where the localhost is listening to the ip,8000 is listening to the port, you can modify it.

In many applications, url rewriting is done, so PHP provides the ability to set up a routing script:

Copy Code code as follows:
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 modification
PHP5.4 new ways to dynamically access static methods:

Copy Code code as follows:
$func = "Funcxxoo";
a::{$func} ();

New features that access class members when instantiated:
Copy Code code as follows:
(New MyClass)->xxoo ();

New support for member access parsing of functions returning arrays (this is an error in previous versions):
Copy Code code as follows:
print func () [0];

PHP5.5 (2013 plays)

Yield
The yield keyword is used to return a value one at a time when the function needs to return an iterator.

Copy Code code as follows:
function Number10 ()
{
for ($i = 1; $i <= $i + + 1)
Yield $i;
}

The return value of the function is an array:
Copy Code code as follows:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

List () for foreach
You can use list () to resolve nested arrays in foreach:
Copy Code code as follows:
$array = [
[1, 2, 3],
[4, 5, 6],
];

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


Results:
Copy Code code as follows:
1 2 3
4 5 6

Details Modification
MySQL function is not recommended, PDO or mysqli is recommended, see the previous article.
Windows XP is no longer supported.
The full qualified name of a class (including namespaces) can be myclass::class.
Empty () supports expressions as arguments.
The TRY-CATCH structure adds a finally block.

PHP5.6

A better constant
Defining a constant allows you to use a previously defined constant for calculation:

Copy 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 Code code as follows:
function func ($arg = c::str2)

Better variable function parameters
Used in place of Func_get_args ()

Copy 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 arguments when calling the function:
Copy Code code as follows:
$arr = [2, 3];
Add (1, ... $arr);

Result is 6
name Space
Namespaces support constants and functions:
Copy 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 ();
}

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.