PH P5.2 to 5.5, 5.6 new features detailed _php Digest

Source: Internet
Author: User
Tags foreach autoload anonymous finally block spl mysql in first row traits

As of today (2014.2), the latest stable version of PHP is PHP5.5, but almost half of the users are still using PHP5.2, which is not in the maintenance [note], and half the rest are using PHP5.3 [note].
Because of PHP's "hundred Family" of the egg pain grammar, coupled with poor community atmosphere, many people on the new version, new features are not interested.
This article will introduce the new features that have been added since PHP5.2 up to PHP5.6.

    • 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

Note: Support was discontinued in January 2011: http://www.php.net/eol.php
Note: Http://w3techs.com/technologies/details/pl-php/5/all

PHP5.2 ago

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

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:

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:

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 ";
}

Releases the result set, closes 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:

    • Object-oriented style interface
    • SQL Precompilation (prepare), placeholder syntax
    • Higher execution efficiency, as an official recommendation, with special performance optimization
    • Supports most SQL databases, replacing databases without changing code

The above code implemented with PDO will be like this:

Connect to database
$conn = new PDO ("Mysql:host=localhost;dbname=database", "User", "password");

Precompiled SQL, binding parameter
$query = $conn->prepare ("SELECT * from" table ' WHERE ' type ' =: type ');
$query->bindparam ("type", $_post[' type '));

Executes the query and prints
The result 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.

Restricts the first argument to MyClass, the second parameter is an executable type, and the third parameter is an array of
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:

$array = ["Key" => "value", "Array" => [1, 2, 3, 4]];
$json = Json_encode ($array);
echo "{$json}\n";

$object = Json_decode ($json);
Print_r ($object);

Output:

{' 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.

Deprecated features

The following features are deprecated, and PHP warns at run time if enabled in the configuration file.

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:

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最小权限原则.

anonymous functions

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

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

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:

Class A
{public
  function __invoke ($str)
  {
    print "A::__invoke (): {$str}";
  }
}

$a = new A;
$a ("Hello world");

The output is undoubtedly:

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:

The delimiter for the <?php
//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;

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

//You can also define a third namespace with curly braces
namespace Other {
  //Instantiate an object from a child namespace:
  $b = new test2\b;

  Import names from other namespaces and rename them,
  //Note Only classes can be imported, 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:

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:

B::funcxxoo

You can see that when used in a$this->funcXXOO() 时,体现了“虚函数”的机制,实际调用的是 B::funcXXOO().
然而如果将所有函数都改为静态函数:

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:

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:

Class A
{
  static public function Callfuncxxoo ()
  {
    print static::funcxxoo ();
  }

  // ...
}

// ...

This will output as expected:

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:

$name = "MyName";
echo <<< TEXT 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:

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:

$name = "MyName";
echo <<< ' TEXT ' My
name is ' {$name} '.
TEXT;

Output:

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:

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:

Correct
const XXOO = 1234;
Error
Const XXOO = 2 * 617;

Ternary operator Shorthand form

Old Style:

echo $a? $a: "No Value";

Can be written by Jane:

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:

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

<?php
//Code ...
? >

This is usually the form above, but there is also a shorthand form:

? /* Code ... * *?>

can also put

<?php echo $xxoo;? >

Jane writes:

<?= $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!

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.

Traits cannot be instantiated separately and can only be included by the class
trait Sayworld
{public
  function SayHello ()
  {
    echo ' world! ';
  }
}

class Myhelloworld
{
  //include members in the Sayworld in the use
  Sayworld;
}

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

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.

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:

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:

$func = "Funcxxoo";
a::{$func} ();

New features that access class members when instantiated:

(New MyClass)->xxoo ();

New support for member access parsing of functions returning arrays (this is an error in previous versions):

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.

function Number10 ()
{for
  ($i = 1; $i <= $i + + 1)
    yield $i;
}

The return value of the function is an array:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

List () for foreach

You can use list () to resolve nested arrays in foreach:

$array = [
  [1, 2, 3],
  [4, 5, 6],
];

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

Results:

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.

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

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:

function func ($arg = c::str2)

Better variable function parameters

Used in place offunc_get_args()

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:

$arr = [2, 3];
Add (1, ... $arr);
Result is 6

Name space

Namespaces support constants and functions:

namespace Name\space {
  const FOO =;
  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.