Brief analysis of PHP7 new function and grammatical change summary _php example

Source: Internet
Author: User
Tags anonymous assert closure deprecated generator intl numeric value parse error

Scalar type declaration

There are two modes: mandatory (default) and strict mode. You can now use the following type parameters, whether in mandatory or strict mode: string, Integer (int), floating-point number (float), and Boolean value (BOOL). In the old version, the parameter declaration of a function can only be (Array $arr), (CLassName $obj), and basic types such as int,string are not allowed to be declared.

<?php
function Check (int $bool) {
var_dump ($bool);
}
Check (1);
Check (TRUE);

enter int (1) bool (true) if there is no forced type conversion. The conversion will output bool (TRUE) bool (true)

return value type declaration

PHP 7 adds support for the return type declaration. The return type declaration indicates the type of the function return value. The available types are the same as those available in the parameter declaration.

<?php
function arrayssum (array ... $arrays): array {return
Array_map (function (array $array): int { C14/>return array_sum ($array);
}, $arrays);
}
Print_r (Arrayssum ([1,2,3], [4,5,6], [7,8,9]);

The above routines will output:

Array
(
[0] => 6
[1] =>
[2] =>
)

Null merge operator

There is a large number of simultaneous use of ternary expressions and isset () in the project, with the addition of the null merge operator (??), the syntactic sugar. If a variable exists and the value is not NULL, it returns its own value, otherwise the second operand is returned.

Old version: Isset ($_get[' id ')? $_get[id]: Err;

NEW: $_get[' id ']?? ' Err ';

Spacecraft operator (combination comparison character)

The spacecraft operator is used to compare two expressions. When $a is less than, equal to, or greater than $b, it returns 1, 0, or 1, respectively.

<?php
//integers
echo 1 <=> 1;/0
Echo 1 <=> 2;//-1
Echo 2 <=> 1;//1
/Fl Oats
Echo 1.5 <=> 1.5//0
echo 1.5 <=> 2.5;//-1
echo 2.5 <=> 1.5;//1
//String S
echo "a" <=> "a";//0
echo "a" <=> "B";//1
echo "B" <=> "a";//1
?>

Defining a constant array by define ()

<?php
define (' ANIMALS ', [' dog ', ' cat ', ' bird ']);
Echo Animals[1]; Outputs "Cat"

Anonymous class

Now supports instantiating an anonymous class with the new class

<?php
interface Logger {public
function log (string $msg);
Class Application {
private $logger;
Public Function GetLogger (): Logger {return
$this->logger;
}
Public Function Setlogger (Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setlogger (new class implements Logger {public
function log (string $msg) {
echo $msg;
}
});
Var_dump ($app->getlogger ());

Unicode codepoint Translation Syntax

This accepts a Unicode codepoint in the form of 16 and prints a string of double quotes or Heredoc enclosed UTF-8 encoded formats. Any valid codepoint can be accepted, and 0 of the beginning can be omitted.

<?php
echo "\u{9876}"

Legacy output: \u{9876}

New input: Top

Closure::call ()

Closure::call () now has better performance, a short and able temporary binding method to the object closure and call it

<?php
class Test{public $name = "Lixuan";}
Both PHP7 and PHP5.6 can
$getNameFunc = function () {return $this->name;};
$name = $getNameFunc->bindto (new test, ' test ');
echo $name ();
PHP7 can, PHP5.6 error
$getX = function () {return $this->name;};
Echo $getX->call (new Test);

Provides filtering for unserialize ()

This feature is designed to provide a more secure way to unpack unreliable data. It prevents potential code injection by means of a whitelist.

<?php
//Divide all objects into __php_incomplete_class objects
$data = Unserialize ($foo, ["Allowed_classes" => false]);
Divides all objects into __php_incomplete_class objects except ClassName1 and ClassName2
$data = unserialize ($foo, ["allowed_classes" => [] ClassName1 "," ClassName2 "]);
The default behavior is the same as the Unserialize ($foo)
$data = Unserialize ($foo, ["Allowed_classes" => true]);

Intlchar

The new Intlchar class aims to expose more ICU functions. This class itself defines a number of static methods for manipulating Unicode characters in multiple character sets. Intl is a pecl extension that needs to be compiled into PHP before use, and can also be apt-get/yum/port install Php5-intl

<?php
printf ('%x ', Intlchar::codepoint_max);
echo intlchar::charname (' @ ');
Var_dump (intlchar::ispunct ('! '));

The above routines will output:

10ffff
Commercial at
BOOL (TRUE)

Expected

is expected to be used backwards and to enhance the previous assert () method. It enables assertions to be zero cost in a production environment and provides the ability to throw a specific exception when an assertion fails. The old version of the API will continue to be maintained for compatibility purposes, and assert () is now a language structure that allows the first argument to be an expression, not just a string to be computed or a Boolean to be tested.

<?php
ini_set (' assert.exception ', 1);
Class Customerror extends Assertionerror {}
assert (False, new Customerror (' Some error message '));

The above routines will output:

Fatal error:uncaught customerror:some Error message

Group Use declarations

Classes, functions, and constants imported from the same namespace can now be imported one at a time through a single use statement.

<?php
//PHP7 before use
Some\namespace\classa;
Use SOME\NAMESPACE\CLASSB;
Use SOME\NAMESPACE\CLASSC as C;
Use function some\namespace\fn_a;
Use function Some\namespace\fn_b;
Use function Some\namespace\fn_c;
Use const Some\namespace\consta;
Use const SOME\NAMESPACE\CONSTB;
Use const SOME\NAMESPACE\CONSTC;
After PHP7 use
Some\namespace\{classa, CLASSB, classc as C};
Use function some\namespace\{fn_a, Fn_b, fn_c};
Use const Some\namespace\{consta, CONSTB, CONSTC};
? >

Intdiv ()

Receives two parameters as dividend and divisor, returning the integer portion of the result of their division.

<?php
Var_dump (Intdiv (7, 2));

Output int (3)

Csprng

Added two functions: Random_bytes () and Random_int (). Can encrypt the production of protected integers and strings. My crappy translation, in short, the random number has become safe.

random_bytes-encrypted live protected pseudo-random strings

random_int-encrypted live protected pseudo-random integer

Preg_replace_callback_array ()

A new function, Preg_replace_callback_array (), is used to make the code more elegant when using the Preg_replace_callback () function. Before PHP7, the callback function invokes each regular expression, and the callback function is contaminated on some branches.

Session options

Now, the session_start () function can receive an array as an argument, overwriting the php.ini of the session.

For example, set the Cache_limiter to private and close immediately after reading the session

<?php
session_start ([
' Cache_limiter ' => ' private ',
' Read_and_close ' => true,
]);

The return value of the generator

Introduce the concept of generator in PHP5.5. Each time the generator function executes, it gets the value of a yield identity. In PHP7, when the generator iteration completes, you can get the return value of the generator function. obtained by Generator::getreturn ().

<?php
Function Generator () {
yield 1;
Yield 2;
Yield 3;
Return "a";
}
$generatorClass = ("generator") ();
foreach ($generatorClass as $val) {
echo $val. " ";
}
echo $generatorClass->getreturn ();

Output is: 1 2 3 A

Other generators introduced in the generator

You can introduce another or several generators in the generator, just write yield from functionName1

<?php
function Generator1 () {
yield 1;
Yield 2;
Yield from Generator2 ();
Yield from Generator3 ();
}
function Generator2 () {
yield 3;
Yield 4;
}
function Generator3 () {
yield 5;
Yield 6;
}
foreach (Generator1 () as $val) {
echo $val, "";
}

Output: 1 2 3 4 5 6

Not compatible

1, foreach no longer changes the internal array pointer

Before PHP7, the array pointer moves when the array passes through a foreach iteration. Start now, no more, see the code below.

<?php
$array = [0, 1, 2];
foreach ($array as & $val) {
var_dump ($array);
}

PHP5 output:

Int (1)
Int (2)
BOOL (FALSE)

PHP7 output:

Int (0)
Int (0)
Int (0)

2, the foreach through the reference traversal, there are better iterative characteristics

When traversing arrays using references, foreach can now better track changes in iterations. For example, to add an iteration value to an array in an iteration, refer to the following code:

<?php
$array = [0];
foreach ($array as & $val) {
var_dump ($val);
$array [1] = 1;
}

PHP5 output:

Int (0)

PHP7 output:

Int (0)
Int (1)

3. A hexadecimal string is no longer considered a number

Contains a hexadecimal string that is no longer considered a number

<?php
var_dump ("0x123" = "291");
Var_dump (Is_numeric ("0x123"));
Var_dump ("0xe" + "0x1");
Var_dump (substr ("foo", "0x1"));

PHP5 output:

BOOL (TRUE)
BOOL (TRUE)
Int (15)
String (2) "oo"

PHP7 output:

BOOL (FALSE)
BOOL (FALSE)
Int (0)
NOTICE:A non formed numeric value encountered in/tmp/test.php on line 5
String (3) "Foo"

4, the removed function in the PHP7

The list of removed functions is as follows:

Call_user_func () and Call_user_func_array () are discarded from the PHP 4.1.0.

The discarded mcrypt_generic_end () function has been removed, please use Mcrypt_generic_deinit () instead.

The discarded MCRYPT_ECB (), MCRYPT_CBC (), MCRYPT_CFB (), and MCRYPT_OFB () functions have been removed.

Set_magic_quotes_runtime (), and its alias Magic_quotes_runtime () has been removed. They have been deprecated in PHP 5.3.0 and have been lost in PHP 5.4.0 due to the abandonment of magic quotes.

The discarded set_socket_blocking () function has been removed, please use stream_set_blocking () instead.

DL () is no longer available in PHP-FPM and is still available in the CLI and embed Sapis.

The following functions are removed from the GD library: Imagepsbbox (), Imagepsencodefont (), Imagepsextendfont (), Imagepsfreefont (), Imagepsloadfont (), Imagepsslantfont (), Imagepstext ()

In the configuration file php.ini, Always_populate_raw_post_data, Asp_tags, xsl.security_prefs are removed.

5. The object created by the new operator cannot be assigned to a variable in a reference way

The object created by the new operator cannot be assigned to a variable in a reference way

<?php
class C {}
$c =& new C;

PHP5 output:

Deprecated:assigning The return value of new by reference is deprecated in/tmp/test.php on line 3

PHP7 output:

Parse error:syntax error, unexpected ' new ' (t_new) in/tmp/test.php on line 3

6. Remove ASP and script PHP tags

The way to differentiate PHP code by using a label like ASP and a script tag is removed. The affected tags are: <%%>, <%=%>, <script language= "PHP" > </script>

7. Initiate a call from a mismatched context

Statically calling non-static methods in mismatched contexts is deprecated in PHP 5.6, but in PHP 7.0 it causes undefined $this variables in the invoked method and warnings that the behavior has been discarded.

<?php
class A {public
function test () {var_dump ($this);}
}
Note: Class
B {public
function Callnonstaticmethodofa () {a::test ()}
is not inherited from type A (New B)->callnonstaticmethodofa ();

PHP5 output:

Deprecated:non-static method A::test () should is called statically, assuming $this from incompatible context in/tmp/ test.php on line 8
object (B) #1 (0) {
}

PHP7 output:

Deprecated:non-static method A::test () should is called statically in/tmp/test.php on line 8
notice:undefined variable:this in/tmp/test.php on line 3

Null

8, when the value overflow, the internal function will fail

When you convert a floating-point number to an integer, if the floating-point value is too large to be expressed as an integer, the internal function truncates the integer directly and does not raise an error in the previous version. In PHP 7.0, if this occurs, a e_warning error is raised and NULL is returned.

9, JSON extension has been replaced by Jsond

JSON extensions have been replaced by Jsond extensions. For numerical processing, there are two points to note: First, the value cannot end with a point number (.) (for example, a value of 34.) Must write 34.0 or 34). Second, if you use scientific notation to represent a value, E must not be preceded by a point number (.) (for example, 3.e3 must write 3.0e3 or 3e3)

10, INI File # annotation format was removed

In the configuration file INI file, the comment line starting with # is no longer supported, use the (semicolon) to represent the comment. This change applies to php.ini and files that are processed with the Parse_ini_file () and parse_ini_string () functions.

11, $HTTP _raw_post_data was removed

$HTTP _raw_post_data variable is no longer available. Please use Php://input as an alternative.

12. Yield change to right join operator

When using the yield keyword, the parentheses are no longer needed, and it is changed to the right join operator, whose operator priority is between print and =>. This can cause the behavior of existing code to change. You can eliminate ambiguity by using parentheses.

<?php
echo yield-1;
The previous version would be interpreted as:
echo (yield)-1;
Now, it will be interpreted as:
Echo yield ( -1);
Yield $foo or die;
In previous versions it would be interpreted as:
yield ($foo or die);
Now, it will be interpreted as:
(yield $foo) or die;

The above is a small set to introduce the analysis of PHP7 new functions and grammatical changes in summary, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.