Understanding and comparison of new characteristics of php7

Time:2020-2-13

1. Null merge operator (?)

Syntax: if the variable exists and the value is not null, it will return its own value, otherwise it will return its second operand

//If judgment before php7 

if(empty($_GET['param'])) { 

  $param = 1; 

}else{ 

 $param = $_GET['param']; 

} 

 

//Pre php7 ternary operator 

$param = empty($_GET['param']) ? 1 : $_GET['param'];

 

//Php7 null merge operator

 

 $param = $_GET['param'] ?? 1;//1

2. Define() defines a constant array

//php7 before 

 define("CONTENT", "hello world"); 

 echo CONTENT;//hello world 

 

 //PHP7 

 define('ANIMALS', [ 

 'dog', 

  'cat', 

 'bird'

]);

 echo ANIMALS[2];//bird

 

 //Const can also be used to define constants outside the php7 class

 const CONSTANT = 'Hello World'; 

 echo CONSTANT;//Hello World

3. Combination comparator (< = >

The combination comparator is used to compare two expressions. When $a is less than, equal to, or greater than $B, it returns – 1, 0, or 1 respectively. The principle of comparison is to follow the regular comparison rules of PHP

Integer 

echo 1 <=> 1; // 0 

echo 1 <=> 2; // -1 

echo 2 <=> 1; // 1 

 

 // floating point number 

echo 1.5 <=> 1.5; // 0 

echo 1.5 <=> 2.5; // -1 

echo 2.5 <=> 1.5; // 1

 

 // String

echo "a" <=> "a"; // 0

echo "a" <=> "b"; // -1

echo "b" <=> "a"; // 1

4. Variable type declaration

There are two modes: mandatory (default) and strict. You can use the following type parameters: string, int, float, bool

//... operator: indicates that this is a variable parameter. Php5.6 and above can be used: before variable when function is defined 

 function intSum(int ...$ints){ 

 return array_sum($ints); 

 } 

var_dump(intSum(2,'3.5'));//5 

 

 //Strict mode 

 //Pattern declaration: declare (strict_types = 1); the default value is 0, and the value 1 represents the pattern of strict verification 

 declare(strict_types=1);

 function add(int $a,int $b){

  return $a+$b;

 }

 var_dump(add(2,'3.5')); //Fatal error: Uncaught TypeError: Argument 2 passed to add() must be of the type integer

5. Return value type declaration

Add support for return type declaration. Similar to parameter type declaration

//Valid return types

declare(strict_types = 1);

 function getInt(int $value): int {

 return $value;

 }

 print(getInt(6));//6
//Invalid return type

declare(strict_types = 1);

 function getNoInt(int $value): int {

 return $value+'2.5';

 }

 print(getNoInt(6));//Fatal error: Uncaught TypeError: Return value of getNoInt() must be of the type integer

6. anonymous category

Allow new class {} to create an anonymous object

<?php 

//Interface implementation before php7 

interface User{ 

 public function getDiscount(); 

} 

class VipUser implements User{ 

 //Discount factor 

 private $discount = 0.6; 

 public function getDiscount() {

  return $this->discount;

 }

}

class Goods{

 private $price = 200;

 private $objectVipUser;

 //User interface vipuser class implementation

 public function getUserData($User){

  $this->objectVipUser = $User;

  $discount = $this->objectVipUser->getDiscount();

  Echo "commodity price:" $this - > price * $discount;

 }

}

$display = new Goods();

//General instantiation interface implementation object

$display - > getuserdata (New vipuser); // product price: 120
<?php 

//Php7 creates an anonymous object 

interface User{ 

 public function getDiscount(); 

} 

class Goods{ 

 private $price = 200; 

 private $objectVipUser; 

 public function getUserData($User){

  $this->objectVipUser = $User;

  $discount = $this->objectVipUser->getDiscount();

  Echo "commodity price:" $this - > price * $discount;

 }

}

$display = new Goods();

//New anonymous object implements user interface

$display ->getUserData(new class implements User{

 private $discount = 0.6;

 public function getDiscount() {

  return $this->discount;

 }

}); // commodity price: 120

7. Closure::call()

The close:: call() method is added as a short way to temporarily bind an object scope to a closure and call it. Compared with PHP 5’s bindto, its performance is much faster

<?php 

//php7 before 

class A { 

 private $attribute = 'hello world'; 

} 

 

$getClosure = function(){ 

 return $this->attribute; 

};

 

$getattribute = $getclosure - > bindto (new a, 'a'); // middle layer closure

echo $getAttribute();//hello world

<?php 

//PHP7 

class A { 

 private $attribute = 'hello world'; 

} 

 

$getClosure = function(){ 

 return $this->attribute; 

};

 

echo $getClosure->call(new A);//hello world

8. unserialize()

Unserialize() function: the feature of filtering, which can prevent illegal data from being injected into code and provide more secure deserialization data

<?php 

 class A{ 

  public $name = 'admin_a'; 

 } 

 class B{ 

  public $name = 'admin_b'; 

 } 

 $objA = new A(); 

 $objB = new B(); 

 $serializedObjA = serialize($objA); 

 $serializedObjB = serialize($objB); 

 //The default behavior is to receive all classes; the second parameter can be ignored

 $dataA = unserialize($serializedObjA , ["allowed_classes" => true]); 

 var_dump($dataA);//object(A)#3 (1) { ["name"]=> string(7) "admin_a" }

//If allowed classes is set to false, unserialize converts all objects to PHP incomplete class objects 

 $dataA = unserialize($serializedObjA , ["allowed_classes" => false]); 

 var_dump($dataA);//object(__PHP_Incomplete_Class)#4 (2) { ["__PHP_Incomplete_Class_Name"]=> string(1) "A" ["name"]=> string(7) "admin_a" }

//Convert all objects to PHP incomplete class objects except object "B"

 $dataB = unserialize($serializedObjB , ["allowed_classes" => ["B"]]); 

var_dump($dataB);//object(B)#3 (1) { ["name"]=> string(7) "admin_b" }

9. IntlChar

Intlchar: provides access to some useful methods that can be used to access Unicode character information. Note: Intl extensions must be installed to use!


var_dump(IntlChar::CODEPOINT_MAX);//int(1114111) 

echo '<br>';

var_dump(IntlChar::charName('+'));//string(9) "PLUS SIGN" 

echo '<br>';

var_dump(IntlChar::ispunct('?'));//bool(true)

10. CSPRNG

The csprng function provides a simple mechanism to generate random numbers of passwords

Random_bytes() – encrypts the existence of a protected pseudo-random string

Random_int() – encrypts the existence of a protected pseudo-random integer

$bytes = random_bytes(8); 

Echo (bin2hex ($bytes)); // random 2073a110a2e3c497

echo '<br>';

Echo (random_int (1, 999)); // random 786

echo '<br>';

Print (random? Int (- 999, - 1)); // random - 357

11. Use statement

Instead of using multiple use statements, you can use a single use statement to import classes, functions, and constants from the same namespace

Before //PHP7 

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

12. intp

The intp() function is added to receive two parameters. The return value is the value of the first parameter divided by the second parameter and rounded


echo intp(8,4);//2

echo intp(10,4);//2

echo intp(5,10);//0

13. Php7 error handling

Unlike the traditional error reporting mechanism of PHP 5, most errors are thrown as error exceptions

This error exception can be caught by the try / catch block like a normal exception. If there is no matching try / catch block, the exception handling function (registered by set_exception_handler()) is called for handling

If the exception handler has not been registered, it is handled in the traditional way: it is reported as a fatal error

The error class is not extended from the exception class, so you can’t catch error with code like catch (exception $e) {…}. You can use code like catch (error $e) {…},

Or catch the error by registering the exception handler function (set_exception_handler())

<?php 

//Custom exception handling before php7 

class getException extends Exception{ 

 public function errorMsg(){ 

  Return 'error message'. $this - > getmessage(). '< br > error code'. $this - > getcode(); 

 } 

} 

 

try {

 $num =10;

 if($num > 1) {

  throw new getException($num,404);

 }

} catch (getException $e) {

 echo $e->errorMsg();

 }
<?php 

//Php7 exception handling

try {

 test();

}catch(Error $e) {

 echo $e->getMessage();//Call to undefined function test()

  }