Home >Backend Development >PHP Problem >Comparison and understanding of new features of php7
?? Syntax: If the variable exists and the value is not NULL, it will return its own value, otherwise it will return its The second operand.
//php7以前 if判断 if(empty($_GET['param'])) { $param = 1; }else{ $param = $_GET['param']; } //php7以前 三元运算符 $param = empty($_GET['param']) ? 1 : $_GET['param']; //PHP7 null合并运算符 $param = $_GET['param'] ?? 1;//1
//php7以前 define("CONTENT", "hello world"); echo CONTENT;//hello world //PHP7 define('ANIMALS', [ 'dog', 'cat', 'bird' ]); echo ANIMALS[2];//bird //PHP7 类外也可使用const来定义常量 const CONSTANT = 'Hello World'; echo CONSTANT;//Hello World
The combined comparison operator is used to compare two expressions. When b, it returns -1, 0 or 1 respectively. The principle of comparison is to follow the regular comparison rules of PHP.
//整数 echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 //浮点数 echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 //字符串 echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1
Two modes: mandatory (default) and strict mode. The following type parameters can be used: string, int, float, bool
//... 操作符: 表示这是一个可变参数. php5.6及以上的版本可使用: 函数定义的时候变量前使用. function intSum(int ...$ints){ return array_sum($ints); } var_dump(intSum(2,'3.5'));//5 //严格模式 //模式声明:declare(strict_types=1); 默认情况值为0,值为1代表为严格校验的模式 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
Add support for return type declaration. Similar to parameter type declaration. (For usage, add: type name after the function definition)
//有效的返回类型 declare(strict_types = 1); function getInt(int $value): int { return $value; } print(getInt(6));//6
//无效返回类型 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
Allows new class {} to create an anonymous object.
<?php //php7以前 接口实现 interface User{ public function getDiscount(); } class VipUser implements User{ //折扣系数 private $discount = 0.6; public function getDiscount() { return $this->discount; } } class Goods{ private $price = 200; private $objectVipUser; //User接口VipUser类实现 public function getUserData(User $User){ $this->objectVipUser = $User; $discount = $this->objectVipUser->getDiscount(); echo "商品价格:".$this->price*$discount; } } $display = new Goods(); //常规实例化接口实现对象 $display->getUserData(new VipUser);//商品价格:120
<?php //php7 创建一个匿名的对象 interface User{ public function getDiscount(); } class Goods{ private $price = 200; private $objectVipUser; public function getUserData($User){ $this->objectVipUser = $User; $discount = $this->objectVipUser->getDiscount(); echo "商品价格:".$this->price*$discount; } } $display = new Goods(); //new匿名对象实现user接口 $display->getUserData(new class implements User{ private $discount = 0.6; public function getDiscount() { return $this->discount; } });//商品价格:120
The Closure::call() method was added as a short way to temporarily bind an object scope to a closure and call it. Its performance is faster compared to PHP5's bindTo. Much more.
<?php //php7以前 class A { private $attribute = 'hello world'; } $getClosure = function(){ return $this->attribute; }; $getAttribute = $getClosure->bindTo(new A, 'A');//中间层闭包 echo $getAttribute();//hello world
<?php //PHP7 class A { private $attribute = 'hello world'; } $getClosure = function(){ return $this->attribute; }; echo $getClosure->call(new A);//hello world
unserialize() function: The filtering feature can prevent illegal data from being injected into the code, providing a safer response Serialized 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); //默认行为是接收所有类; 第二个参数可以忽略 $dataA = unserialize($serializedObjA , ["allowed_classes" => true]); var_dump($dataA);//object(A)#3 (1) { ["name"]=> string(7) "admin_a" } //如果allowed_classes设置为false,unserialize会将所有对象转换为__PHP_Incomplete_Class对象 $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" } //转换所有对象到 __PHP_Incomplete_Class对象,除了对象"B" $dataB = unserialize($serializedObjB , ["allowed_classes" => ["B"]]); var_dump($dataB);//object(B)#3 (1) { ["name"]=> string(7) "admin_b" }
IntlChar: Provides access to some practical methods that can be used to access Unicode character information. Note: The Intl extension 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)
The CSPRNG function provides a simple mechanism to generate random numbers for passwords.
random_bytes() - A cryptographically protected pseudo-random string.
random_int() - A cryptographically protected pseudo-random integer.
$bytes = random_bytes(8); echo(bin2hex($bytes));//随机2073a110a2e3c497 echo '<br>'; echo(random_int(1, 999));//随机786 echo '<br>'; print(random_int(-999, -1));//随机-357
You can use a single use statement to import classes, functions and constants from the same namespace instead of using multiple use statements.
//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; // 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};
The newly added intdiv() function receives two parameters, and the return value is the value of the first parameter divided by the second parameter and rounded.
echo intdiv(8,4);//2 echo intdiv(10,4);//2 echo intdiv(5,10);//0
PHP7 has changed the way most errors are reported. Unlike PHP5’s traditional error reporting mechanism, most errors are now thrown as Error exceptions.
This Error exception can be treated like a normal exception Caught by a try/catch block. If there is no matching try/catch block, the exception handling function (registered by set_exception_handler()) is called for processing.
If the exception handling function has not been registered, it is processed in the traditional way : Reported as a fatal error (Fatal Error).
The Error class is not extended from the Exception class, so code such as catch (Exception $e) { ... } cannot catch Error . You can use code like catch (Error $e) { ... } or catch Error by registering an exception handling function (set_exception_handler()).
<?php //php7以前 自定义异常处理 class getException extends Exception{ public function errorMsg(){ return '错误的信息'.$this->getMessage().'<br>错误的代码'.$this->getCode(); } } try { $num =10; if($num > 1) { throw new getException($num,404); } } catch (getException $e) { echo $e->errorMsg(); }
<?php //php7 异常处理 try { test(); }catch(\Exception $e){ echo $e->getMessage();//自定义异常抛出 }catch(\Error $e) { //系统错误 echo $e->getMessage();//Call to undefined function test() }For more PHP related knowledge, please visit PHP Chinese website
The above is the detailed content of Comparison and understanding of new features of php7. For more information, please follow other related articles on the PHP Chinese website!