After reading this article, you will understand why the domestic PHP environment and ThinkPHP use PHP5.3 or higher.
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 “combines the strengths of hundreds of schools of thought” , coupled with 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 until PHP5.6. 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 form, Traits, built-in Web server, detailed modifications
PHP5.5: yield, list() for foreach, Detailed modifications
PHP5.6: constant enhancement, variable function parameters, namespace enhancement
Note: Stopped support 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 of PHP5.2 that have already appeared but are worth introducing. autoloadEveryone 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, and you can load it in this function Corresponding class implementation files, such as:
-
function__autoload($classname){
-
require_once ("{$classname}.php" )
-
}
Copy code
But this function is no longer recommended because there can only be one such __autoload() function in a project, because PHP does not Duplicate function names are allowed. But when you use some class libraries, you will inevitably need multiple autoload functions, so spl_autoload_register() replaces it:
-
spl_autoload_register(function($classname)
-
{
-
require_once("{$classname}.php")
-
});
Copy code
spl_autoload_register() will A function is registered in 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. This means that you can use spl_autoload_register() to register multiple autoloads.
Function.Note: SPL: Standard PHP Library, standard PHP library, is designed to solve some classic problems (such as data structure).PDO and MySQLiThat 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 be like this:
- // Connect to the server, 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)
-
"{$k}: {$v}n" ; }
-
- // Release the result set, close the connection
-
mysql_free_result(
- $result);mysql_close (
- $conn);Copy code
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, For example: ? Object-oriented style interface ? SQL precompilation (prepare), placeholder syntax ? Higher execution efficiency, as an official recommendation, there is special performance optimization ? support For most SQL databases, there is no need to change the code when changing the databaseThe above code implemented with PDO will be like this:
- //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 the query and print the results
-
foreach($query->execute() as $row )
-
{
-
foreach($row as$k => $v)
-
"{$k}: {$v}n";
- }
Copy code
PDO is officially recommended and a more general database access method, if If you have no special needs, then you'd better learn and use PDO.
But if you need to use the advanced features unique to MySQL, then you may need to try MySQLi, because PDO cannot be used on multiple databases at the same time. Will contain features that are 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 constraintsThe 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.
- // Restrictions The first parameter is MyClass, the second parameter is the executable type, and the third parameter is the array
-
function MyFunction(MyClass $a, callable $b, array $c)
-
{
-
Copy code-
PHP5. 2(2006-2011)
JSON supportincludes 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 JS syntax part.
JSON series of functions can convert array structures in PHP into JSON strings: $array = array(
- "key"=> "value", "array"=> , 3, 4));$json = json_encode($array);echo "{$json}n";
-
$object = json_decode(
- $json);print_r
- ( $object
- );Copy code Output: {
- "key":"value","array"
:[1
,2
- ,3 ,4]}stdClass Object ( ) [key ]
-
=> value
- [
- array]=>Array
-
1 ~ 3
-
)
-
)Copy CodeIt 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. Deprecated FeaturesThe following features are deprecated. If enabled in the configuration file, PHP will issue a warning at runtime. Register GlobalsThis is an option in php.ini (register_globals). When turned on, all form variables ($_GET and $_POST) will be registered as global variables. Look at the example below:
-
if(isAuth())
-
$authorized = true;
-
if ($authorized)
-
include("page.php");
Copy code
When this code passes verification, set $authorized to true. Then decide whether to display it based on the value of $authorized Page.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. In Chapter 1, we mentioned escaping user input. 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 ModeMany 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 functions Also called closures, they are often used to temporarily create an unnamed function for callback functions and other purposes.
-
$func = function($arg)
-
{
-
print $arg;
-
};
-
$func("Hello World");
Copy code
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 it is 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:
-
function arrayPlus($array,$num)
- {
-
array_walk($array, function(&$v) use ($num){
-
$v += $num;
-
});
-
}
Copy code
The above code defines an arrayPlus() function ( This is not an anonymous function), it adds a specified number ($num) to each item in an array ($array).In the implementation of arrayPlus(), we use array_walk() Function, it 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. A {
- public
- function__invoke(
- $str) { print
- "A::__invoke(): {$str}";
- = new A;
-
$a(
"Hello World"-
);
- Copy the code
The output is undoubtedly: -
A :: __invoke():
Hello-
WorldCopy code
__callStatic() will be called when a non-existent static method is called. Namespace
PHP’s namespace has an extremely painful syntax that is unprecedented and unprecedented:
- php// The delimiter of the namespace is a backslash , the declaration statement must be on the first line of the file. // The namespace can contain any code, but only **classes, functions, and 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 next code will be located in OtherTest2.
-
namespace- Other
Test2- ;
- // Instantiate objects from other namespaces:
- $a =
- You can also use it Curly braces define the third namespace namespace Other
- {
- // Instantiate objects from sub-namespaces:
- $b = newTest2 B
- ; // Import names from other namespaces and rename them,
- // Note that only classes can be imported, not functions and constants.
- use
- XXOOTestA as ClassA }
- Copy code
For more introduction to the syntax of namespace, please see the official website [Note]. Namespace is often used together with autoload to automatically load class implementation files: - spl_autoload_register(
- function($class){
- "\", "/", $class)); estA, the fully qualified name of this class Will be 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
Later static binding
PHP’s OPP mechanism has inheritance and virtual function-like functions, such as the following code: - class
function
callFuncXXOO() { - print $this->
- funcXXOO();
- } public
- function funcXXOO
- () { return
- "A::funcXXOO()";
-
- } }
- class
- A {
- public function
- funcXXOO()
- “B::funcXXOO” ;
-
} }
-
- $b = new B;
- $b->call FuncXXOO
- ();Copy The output of the code is:
- B::funcXXOO
-
Copy the code
You can see that when $this->funcXXOO() is used in A, the "virtual function" mechanism is reflected, and B::funcXXOO() is actually called. However, if all functions are changed Is a static function:
-
class
callFuncXXOO-
()
-
{ static
public-
function
funcXXOO-
() "A::funcXXOO()" ;}
-
}
-
class B extendsA static public
-
function funcXXOO
()-
}
}-
-
$b =
- new
B-
;$b->callFuncXXOO
();-
Copy the code
-
The situation will be fine So optimistic, the output is: A::funcXXOO()Copy code
-
This is because the semantics of self is originally "current class", so PHP5.3 A new function is given to the static keyword: late static binding:
class-
function callFuncXXOO ()
- {
- ();
- }
-
//… }
-
//…
Copy the code
and it will be as expected Output: - B::funcXXOO
Copy code
Heredoc and NowdocPHP5.3 has made 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:
- $name =
- "MyName";echo << ; TEXT My
- name is
- "{$name}".TEXT; 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 a double quoted string, variables can be embedded in it. Heredoc can also be used for function parameters and class member initialization: - var_dump(<<<EOD
- Hello World
- EOD
- );
- class
- constxx =
- << " public $oo = < <<EOD
- HelloWorld
- EOD;
- Copy code
- Nowdoc behaves like a single Quoted strings cannot embed variables in them. The only difference from Heredoc is that the identifier after the three left angle brackets must be enclosed in single quotes: $name = "MyName" ;
- echo << "{$name}".
- TEXT;
- Copy codeOutput:
My
name is- "{$name}" .Copy code
- Use const to define constants Starting from PHP 5.3, it supports using const to define constants in both the global namespace and classes. Old style:
- define("XOOO", "Value");
- Copy Code New style:
const
XXOO =- "Value";Copy code const form only applies to constants, not expressions that can be evaluated at runtime:
//Correct
constXXOO=- 1234;//Wrong
constXXOO
= - 2* 617;
Copy code
Ternary operator short formOld style: - echo $a
- ? $a : "No Value";
Copy code- can be abbreviated as:
- echo $a ?: "No Value";
Copy code
That is, if the second part of the ternary operator is omitted, The first part will be used instead by default. PharPhar 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: - require( "xxoo.phar" ); 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 TagShort Open Tag is always available since PHP5.4.
Here we will focus on the issues related to PHP start and end tags. That is:
php // Code... ?>
- Copy code Usually the form above, except In addition, there is an abbreviated form:
-
/* Code... */- ?>
Copy the code
You can also put -
php echo $xxoo;?>Copy the code
abbreviated to:
= $xxoo- ;?> Copy code
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 box and omitting the end tag. This ensures that the entire PHP file is PHP code without any output, otherwise when you include the file, you will encounter some trouble when setting the Header and Cookie [Note].Note: Header and Cookie are required Sent before anything is output. Array abbreviationThis is a very convenient feature!
- //Original array writing
-
$arr = array("key" => "value", "key2" => ["key "
-
=> ];
-
Copy code TraitsThe 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 cannot be instantiated individually and can only be contained by classestrait SayWorld { echo 'World!'; }
}
- class
- MyHelloWorld
- {
- //Include members from SayWorld use SayWorld
- ;
- }
- $xxoo MyHelloWorld();
-
// The sayHello() function is from the SayWorld component
-
$xxoo
- ->sayHello();
Copy code-
Traits also have many magical functions, such as containing multiple Traits, resolve conflicts, modify access permissions, set 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 the development environment.
-
php -S localhost:8000
Copy the code
This will establish a Web server in the current directory. You can pass http://localhost:8000 / to visit. 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: -
php -S localhost:8000index. php
Copy the code
In this way, all requests will be processed by index.php. You can also use XDebug for breakpoint debugging. Details modificationPHP5.4 adds a new way to dynamically access static methods:
-
$func = "funcXXOO";
-
A::{ $func}();
Copy code
New feature to access class members during instantiation:-
(new MyClass)-> xxoo();
Copy code
Added support for member access analysis of function return arrays (this writing method will report an error in previous versions): -
print func ()[0];
Copy code
PHP5.5(2013 onwards)yieldyield keyword is used when the function needs to return an iterator, Return values one by one.
-
functionnumber10()
-
{
-
= 1; $i <= 10; $i += 1) $i;
-
} Copy code
-
The return value of this function is an array: list() is used for foreachYou can use list() to parse nested arrays in foreach:
-
$array = [
-
[1, 2, 3],
-
], ]; foreach
-
($array
as- list
(-
$a,$b , $c)) echo 3 45
-
6Copy code
Details modificationIt is not recommended to use mysql function, it is recommended to use PDO or MySQLi, see above.
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 new finally block is added to the try-catch structure.
- PHP5.6Better constantsWhen defining constants, you can use previously defined constants for calculations: const A =
2
; const B = A + 1;
-
class C {
-
const STR = "hello"; ::
- STR +
- ", world ";
- }
-
Copy codeAllow constants as function parameters default values: function func( $arg
- = C ::STR2)Copy codeBetter variadic function parametersUsed to replace func_get_args()
-
function add(...$args)
-
{
-
$res ult = 0 ;
-
+= $arg; return $result
- ; }
-
Copy the codeAt the same time, when calling the function, the array can be expanded into function parameters: $arr
- = [
2,
3
- ];add(1, ... $arr);
-
//The result is 6Copy code Namespace Namespace supports constants and functions:
- namespace Name
Space {
const
- FOO = 42;
- echo __FUNCTION__."n"; }
-
} namespace use const Name
SpaceFOO-
; cho FOO.
"n"- ;
-
f ();
}-
The above has introduced a detailed explanation of the new functions of PHP52 to 56, including relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.
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