In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the new features and features of each version of PHP5". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the new features and features of each version of PHP5?"
The contents of this article:
Before PHP5.2: autoload, PDO and MySQLi, type constraints
PHP5.2:JSON support
PHP5.3: deprecated functions, anonymous functions, new magic methods, namespaces, late static binding, Heredoc and Nowdoc, const, ternary operators, Phar
PHP5.4:Short Open Tag, array abbreviation, Traits, built-in Web server, details modification
PHP5.5:yield, list () for foreach, details modification
PHP5.6: constant enhancement, variable function arguments, namespace enhancement
I. before PHP5.2 (before 2006)
By the way, I'd like to introduce some features of PHP5.2 that have emerged but are worth introducing.
Autoload
You may all know the _ _ autoload () function. If the function is defined, it will be called when an undefined class is used in the code. You can load the corresponding class implementation file in the function, such as:
The copy code is as follows:
Function _ _ autoload ($classname)
{
Require_once ("{$classname} .php")
}
However, this function is no longer recommended because there can be only one such _ _ autoload () function in a project, because PHP does not allow functions to have duplicate names. But when you use some class libraries, there will inevitably be the need for multiple autoload functions, so spl_autoload_register () takes its place:
The copy 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. When an undefined class appears, SPL [Note] calls the registered autoload functions one by one in reverse order of registration, which means you can use spl_autoload_register () to register multiple autoload functions.
Note: SPL: Standard PHP Library, the standard PHP library, is designed to solve some classic problems (such as data structures).
PDO and MySQLi
Namely PHP Data Object, PHP data object, this is the new database access interface of PHP.
In traditional style, accessing the MySQL database should look like this:
The copy 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 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)
In order to make the code database-independent, that is, a piece of code can be applied to multiple databases at the same time (for example, the above code is only applicable to MySQL), PHP officially designed PDO.
In addition, PDO provides more features, such as:
1. Object-oriented interface
2.SQL precompilation (prepare), placeholder syntax
3. Higher execution efficiency, as an official recommendation, with special performance optimization
4. Most SQL databases are supported. No code changes are required to replace the database.
The above code will be implemented in PDO like this:
The copy code is as follows:
/ / Connect to the database
$conn = new PDO ("mysql:host=localhost;dbname=database", "user", "password")
/ / precompile SQL, bind parameters
$query = $conn- > prepare ("SELECT * FROM `table`WHERE `type` =: type")
$query- > bindParam ("type", $_ POST ['type'])
/ / execute query and print results
Foreach ($query- > execute () as $row)
{
Foreach ($row as $k = > $v)
Print "{$k}: {$v}\ n"
}
PDO is officially recommended, a more general way to access the database, if you do not 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 may want to try MySQLi, because PDO does not include those features 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, which provides both process-oriented and object-oriented interfaces. It is also the recommended MySQL driver. The old C-style MySQL interface will be turned off by default in the future.
Compared with the above two pieces of code, there are not many new concepts in the usage of MySQLi. No more examples are given here. Please refer to the official website of PHP [Note].
Note: http://www.php.net/manual/en/mysqli.quickstart.php
Type constraint
Type constraints can limit the types of parameters, but this mechanism is not perfect. At present, it is only applicable to classes and callable (executable types) and array (arrays), but not to string and int.
The copy code is as follows:
/ / limit the first parameter to MyClass, the second to executable type, and the third to 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 data exchange format in the field of Web, which can be directly supported by JS. JSON is actually a part of JS syntax.
JSON series functions that convert array structures in PHP to JSON strings:
The copy code is 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:
The copy 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 () returns 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, with a lot of new features and some incompatible changes.
[PHP5.3 deprecated function]: the following features are deprecated. If enabled in the configuration file, PHP will issue a warning at run time.
Register Globals
This is an option in php.ini (register_globals). When enabled, all form variables ($_ GET and $_ POST) are registered as global variables.
Look at the following example:
The copy code is as follows:
If (isAuth ())
$authorized = true
If ($authorized)
Include ("page.php")
When this code passes the verification, set $authorized to true. Then decide whether or not to display the page based on the value of $authorized.
However, 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, bypassing authentication.
This feature is a historical legacy and is turned off 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 historical legacy and has been removed from PHP5.4.
This feature escapes all user input, which looks good, as we mentioned in the first chapter.
But PHP doesn't know which inputs go into SQL, which inputs go into Shell, and which inputs are displayed as HTML, so in many cases this escape can cause confusion.
Safe Mode
Many web hosting providers use Safe Mode to isolate multiple users, but Safe Mode has many problems, such as some extensions do not control permissions according to Safe Mode.
PHP officially recommends using the operating system's mechanism for privilege isolation to allow Web servers to run the PHP interpreter with different user rights. See the minimum privilege principle in Chapter 1.
[addition and improvement of PHP5.3]
Anonymous function
Also known as Closures, it is often used to temporarily create an unnamed function for purposes such as callback functions.
The copy code is as follows:
$func = function ($arg)
{
Print $arg
}
$func ("Hello World")
The above code defines an anonymous function and assigns a value to $func.
You can see that defining anonymous functions still uses the function keyword, except that the function name is omitted and is directly a parameter list.
Then we call the anonymous function stored in $func.
Anonymous functions can also use the use keyword to capture external variables:
The copy 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 each item in an array ($array) to 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, the anonymous function we define.
After the argument list of the anonymous function, we use the use keyword to capture the $num outside the anonymous function into the function to know exactly how much should be added.
Magic method: _ _ invoke (), _ _ callStatic ()
In the object-oriented architecture of PHP, several "magic methods" are provided to implement "overloads" similar to those in other languages, such as triggering a magic method when accessing properties or methods that do not exist.
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:
The copy 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 copy code is as follows:
A::__invoke (): Hello World
_ _ callStatic () is called when a static method that does not exist is called.
Namespace
PHP's namespace has a painful syntax that has never been seen before:
The copy code is as follows:
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.