Home >Backend Development >PHP Tutorial >Summary of new functions and features of PHP5_PHP Tutorial

Summary of new functions and features of PHP5_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:35:53834browse

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 in PHP5.2 starting from PHP5.6. ​ ​

Directory of this article:
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 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

1. Before PHP5.2 (before 2006)
By the way, let me introduce the features of PHP5.2 that have already appeared 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:

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:
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
are 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:

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:

1. Object-oriented style interface
2. SQL pre-compilation (prepare), placeholder syntax
3. Higher execution efficiency, as an official recommendation, there are special performance optimizations
4 .Supports most SQL databases, no need to change the code when changing the database

The above code implemented using PDO will look like this:

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 results
foreach($query->execute() as $row)
{
foreach($row as $k => $v)
print "{$k}: {$v}n";
} (Edited and organized by Script Academy www.jbxue.com)


PDO is officially recommended and 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 the advanced functions unique to MySQL, then you may You need to try MySQLi, because in order to be able to be used on multiple databases at the same time, PDO does not include features unique to MySQL.

MySQLi is an enhanced interface for MySQL, providing 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
Type constraints can limit the type of parameters, but this mechanism is not perfect and currently only applies to classes, callables (executable types) and arrays (arrays), not Applies to string and int.

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)
{
// ...
}

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:

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,3,4]}
stdClass Object
(
[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 made some modifications that are not backward compatible.
【PHP5.3 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 in php.ini (register_globals). When turned on, all form variables ($_GET and $_POST) will be registered as global variables.
See Example below:

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 because $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 value of this variable 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.

[New additions and improvements in PHP5.3]

Anonymous functions
are also called closures and are often used to temporarily create an unnamed function for callback functions and other purposes.

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 the anonymous function, 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 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 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. For example, a magic method is triggered when accessing non-existent properties or methods.
With the addition of anonymous functions, PHP introduces a new magic method __invoke().
This magic method will be called when an object is called as a function:

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:
The code is as follows: 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:

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 following 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 information on the syntax of namespaces, please see the official website [Note].
Namespaces are often used together with autoload to automatically load class implementation files:


spl_autoload_register(
function ($class) {
spl_autoload(str_replace("\", "/", $class));
}
);
when When you instantiate a class XXOOTestA, the fully qualified name of the class is passed to the autoload function, which replaces the namespace separator (backslash) in the class name with a slash and includes the corresponding file.
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, with inheritance and virtual function-like functions, such as the following 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:
The code is as follows: B::funcXXOO
You can see that when $this->funcXXOO() is used in A, the "virtual function" mechanism is reflected, and what is actually called is B::funcXXOO().
However, if all functions are All changed to static functions:
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:
The code is as follows: A::funcXXOO()
This is because the semantics of self is "current class", so PHP5.3 gives the static keyword a new function: late static binding:
The code is as follows: class A
{
static public function callFuncXXOO()
{
print static::funcXXOO();
}

// ...
}

// ...


This will output as expected:
The code is as follows: 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:

The code is as follows: $name = "MyName";
echo <<< TEXT
My name is "{$name}".
TEXT;
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:

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

PHP 5.3 and later supports the use of const to define constants in both the global namespace and classes.
Old style:

The code is as follows: define("XOOO", "Value");
New style:
const XXOO = "Value";
The const form is only suitable for constants, not for expressions that can be evaluated at runtime:
The code is as follows: // Correct
const XXOO = 1234;
// Incorrect
const XXOO = 2 * 617;

Ternary operator short form
Old style:

The code is as follows: echo $a ? $a : "No Value";
can be abbreviated as:
The code is as follows: 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 (can also package other files) 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:

The code is as follows: require("xxoo.phar");
require("phar://xxoo.phar/xo/ox.php");
For more information, please see 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:

The code is as follows: // Code...
?>
is usually the above form, in addition there is also an abbreviated form:
The code is as follows:
You can also use it
The code is as follows:
is abbreviated as:
The code is as follows:
This abbreviation is called Short Open Tag, which is enabled by default in PHP5.3 and always available in PHP5.4.
Using this shorthand form will 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!

The code is as follows: //Original array writing method
$arr = array("key" => "value", "key2" => "value2");
// Short form
$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.

The code is as follows: // Traits cannot be instantiated individually and can only be included in classes
trait SayWorld
{
public function sayHello()
{
echo 'World!';
}
}

class MyHelloWorld
{
// Include members from SayWorld
use SayWorld;
}

$xxoo = new MyHelloWorld();
// The sayHello() function is from the SayWorld component
$xxoo->sayHello();


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 refer to 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.

The code is as follows: php -S localhost:8000
This will establish a web server in the current directory, which you can access through http://localhost:8000/.
Where 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:

The code is 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.

Modified details
PHP5.4 adds a new way to dynamically access static methods:

The code is as follows: $func = "funcXXOO";
A::{$func}();
New feature for accessing class members during instantiation:
The code is as follows: (new MyClass)->xxoo();
Added support for member access analysis of function return arrays (this writing method would report an error in previous versions):
The code is as follows: print func()[0];

PHP5.5(2013 onwards)

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
It is not recommended to use the mysql function. 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, allow calculations using previously defined constants:

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:
The code is as follows: function func($arg = C::STR2)

Better variadic function arguments
used instead of func_get_args()

The code is as follows: function add(...$args)
{
$result = 0;
foreach($args as $arg)
$result += $arg;
return $result;
}
At the same time, when calling a function, the array can be expanded into function parameters:
The code is as follows: $arr = [2, 3];
add(1, ...$arr);
// The result is 6
Namespace
The namespace supports constants and functions:
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();
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/742101.htmlTechArticleBecause of PHP’s painful syntax and the poor community atmosphere, many people are skeptical of new Version, new features are not of interest. This article will introduce the features added in PHP5.2 until PHP5.6...
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