Home  >  Article  >  Backend Development  >  Detailed explanation of new features of PHP52 to 56

Detailed explanation of new features of PHP52 to 56

WBOY
WBOYOriginal
2016-07-30 13:29:251526browse

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. 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, and you can load it in this function Corresponding class implementation files, such as:

    1. function__autoload($classname){
    2. require_once ("{$classname}.php" )
    3. }

    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:

    1. spl_autoload_register(function($classname)
    2. {
    3. require_once("{$classname}.php")
    4. });

    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:
    1. // Connect to the server, select the database
    2. $conn = mysql_connect("localhost" ,"user","password");
    3. mysql_select_db("database") ;
    4. // Execute SQL query
    5. $type = $_POST['type'];
    6. $sql = "SELECT * FROM `table` WHERE `type` = {$type}";
    7. $result = mysql_query($sql);
    8. //Print results
    9. while($row = mysql_fetch_array($result, MYSQL_ASSOC ))
    10. {
    11. foreach($row as $k => $v)
    12. "{$k}: {$v}n" ; }
    13. // Release the result set, close the connection
    14. mysql_free_result(
    15. $result);mysql_close (
    16. $conn);Copy code
    17. 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:
      1. //Connect to the database
      2. $conn =new PDO("mysql:host=localhost;dbname=database", "user", "password");
      3. //Precompile SQL, bind parameters
      4. $query = $conn->prepare("SELECT * FROM `table` WHERE `type` = :type ");
      5. $query->bindParam("type", $_POST['type' ]);
      6. //Execute the query and print the results
      7. foreach($query->execute() as $row )
      8. {
      9. foreach($row as$k => $v)
      10.                                                                                                                                                       "{$k}: {$v}n";
      11. }
      12. 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.
      1. // Restrictions The first parameter is MyClass, the second parameter is the executable type, and the third parameter is the array
      2. function MyFunction(MyClass $a, callable $b, array $c)
      3. {
      4. Copy code
      5. PHP5. 2(2006-2011)
      JSON support

      includes 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(
      1. "key"=> "value", "array"=> , 3, 4));$json = json_encode($array);echo "{$json}n";
      2. $object = json_decode(
      3. $json);print_r
      4. ( $object
      5. );Copy code Output: {
      6. "key":"value","array"
      :[

      1

      ,2
      1. ,3 ,4]}stdClass Object ( ) [key ]
      2. => value
      3. [
      4. array]=>Array
      5.                                                                                                              ​ 1                                                                                                              ~ 3
      6.                                                                                                          
      7.                )
      8.  )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:
        1. if(isAuth())
        2. $authorized = true;
        3. if ($authorized)
        4. 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.
        1. $func = function($arg)
        2. {
        3. print $arg;
        4. };
        5. $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:
        1. function arrayPlus($array,$num)
        2. {
        3.        array_walk($array, function(&$v) use ($num){
        4. $v += $num;
        5. });
        6. }

        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 {
        1. public
        2. function__invoke(
        3. $str) { print
        4. "A::__invoke(): {$str}";
        5.                                                         = new A;
        6. $a(
        7. "Hello World"
        8. );
        9. Copy the code
        10. The output is undoubtedly:
        11. A :: __invoke():
        12. Hello
        13. 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:
        1. 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;

        1. // The fully qualified name of this class is XXOOTestA , where the first backslash indicates the global namespace.
        2. class
        3. A{}
        4. /// You can also define a second namespace in the existing file, and the next code will be located in OtherTest2.
        5. namespace
        6. Other
        7. Test2
        8. ;
        9. // Instantiate objects from other namespaces:
        10. $a =
        11. You can also use it Curly braces define the third namespace namespace Other
        12. {
        13. // Instantiate objects from sub-namespaces:
        14. $b = newTest2 B
        15. ; // Import names from other namespaces and rename them,
        16. // Note that only classes can be imported, not functions and constants.
        17. use
        18. XXOOTestA as ClassA }
        19. Copy code
        20. 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:
          1. spl_autoload_register(
          2. function($class){
          3. "\", "/", $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.
          4. Note: http://www.php.net/manual/zh/language.namespaces.php Later static binding
          5. PHP’s OPP mechanism has inheritance and virtual function-like functions, such as the following code:
          6. class

          function

          callFuncXXOO() {

          1. print $this->
          2. funcXXOO();
          3. ​​​} public
          4. function funcXXOO
          5. () {          return
          6.  "A::funcXXOO()";
          7. } }
          8. class
          9. A {
          10. public function
          11. funcXXOO()
          12. “B::funcXXOO” ;
          13. ​​​} }
          14. $b = new B;
          15. $b->call FuncXXOO
          16. ();Copy The output of the code is:
          17. B::funcXXOO
          18. Copy the code
          19. 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:
            1. class
            2. callFuncXXOO
            3. ()
            4. ​​​​
            5. {                                                                                                                                         static
            6. public
            7. function
            8. funcXXOO
            9. () "A::funcXXOO()" ;​​​}
            10. }
            11. class B extendsA​ static public
            12. function funcXXOO
            13. ()
            14.                                                           }
            15. }
            16. $b =
            17. new
            18. B
            19. ;$b->callFuncXXOO
            20. ();
            21. Copy the code
            22. The situation will be fine So optimistic, the output is: A::funcXXOO()Copy code
            23. 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:
            24. class
            25. function callFuncXXOO ()
            26. {
            27. ();​​​
            28. }
            29. //… }
            30. //…

            Copy the code

            and it will be as expected Output:
            1. 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 .
            1. Heredoc behaves like a double-quoted string:
            2. $name =
            3. "MyName";echo << ; TEXT My
            4. name is
            5. "{$name}".TEXT; Copy code
            6. 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:
              1. var_dump(<<<EOD
              2. Hello World
              3. EOD
              4. );
              5. class
              6. constxx =
              7. << " public $oo = < <<EOD
              8. HelloWorld
              9. EOD;
              10. Copy code
              11. 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" ;
              12. echo << "{$name}".
              13. TEXT;
              14. Copy codeOutput:

              My

              name is
              1. "{$name}" .Copy code
              2. 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:
              3. define("XOOO", "Value");
              4. Copy Code New style:

              const

              XXOO =
              1. "Value";Copy code const form only applies to constants, not expressions that can be evaluated at runtime:

              //Correct

              constXXOO=
              1. 1234;//Wrong
              const

              XXOO

              =
              1. 2* 617;

              Copy code

              Ternary operator short formOld style:
              1. echo $a
              2. ? $a : "No Value";
              3. Copy code
              4. can be abbreviated as:
                1. 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. 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:
                1. require( "xxoo.phar" ); For more information, please see the official website [Note].
                2. 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...

                ?>
                1. Copy code Usually the form above, except In addition, there is an abbreviated form:
                2. /* Code... */
                3. ?>

                Copy the code

                You can also put
                1. php echo $xxoo;?>Copy the code

                abbreviated to:

                  $xxoo
                1. ;?> 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!
                1. //Original array writing
                2. $arr = array("key" => "value", "key2" => ["key "
                3. => ];
                4. 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!'; }

                }

                1. class
                2. MyHelloWorld
                3. {
                4. //Include members from SayWorld use SayWorld
                5. ;
                6. }
                7. $xxoo MyHelloWorld();
                8. // The sayHello() function is from the SayWorld component
                9. $xxoo
                10. ->sayHello();
                11. Copy code
                12. Traits also have many magical functions, such as containing multiple Traits, resolve conflicts, modify access permissions, set aliases for functions, etc.
                13. 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].
                14. Note: http://www.php.net/manual/zh/language.oop5.traits .php
                15. Built-in web server
                16. 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.
                  1. 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:
                  1. 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:
                  1. $func = "funcXXOO";
                  2. A::{ $func}();

                  Copy code

                  New feature to access class members during instantiation:
                  1. (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):
                  1. 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.
                  1. functionnumber10()
                  2. {
                  3. = 1; $i <= 10; $i += 1) $i;
                  4. } Copy code
                  5. The return value of this function is an array: list() is used for foreachYou can use list() to parse nested arrays in foreach:
                    1. $array = [
                    2. [1, 2, 3],
                    3. ], ]; foreach
                    4. ($array
                    5. as
                    6. list
                    7. (
                    8. $a,$b , $c)) echo 3 45
                    9. 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.
                    1. 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.
                    2. PHP5.6Better constantsWhen defining constants, you can use previously defined constants for calculations: const A =

                    2

                    ; const B = A + 1;
                    1. class C {
                    2. const STR = "hello"; ::
                    3. STR +
                    4. ", world ";
                    5. }
                    6. Copy codeAllow constants as function parameters default values: function func( $arg
                    7. = C ::STR2)Copy codeBetter variadic function parametersUsed to replace func_get_args()
                      1. function add(...$args)
                      2. {
                      3. $res ult = 0 ;
                      4.                                                                                                                                            += $arg; return $result
                      5. ; }
                      6. Copy the codeAt the same time, when calling the function, the array can be expanded into function parameters: $arr
                      7. = [
                      2

                      ,

                      3
                      1. ];add(1, ... $arr);
                      2. //The result is 6Copy code Namespace Namespace supports constants and functions:
                      3. namespace Name
                      Space

                      {

                      const
                      1. FOO = 42;
                      2. echo __FUNCTION__."n"; }
                      3. } namespace use const Name
                      4. SpaceFOO
                      5. ; ​​​cho FOO.
                      6. "n"
                      7. ;
                      8.        f ();
                      9. }
                      10. 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