PHP7中新的语法特性

PHP7语法新特性

  • 太空船操作符
/* 用于比较两个表达时, 在小于,大于,等于时分别返回-1, 0, 1*/
echo 1 <=> 2; 	// -1
echo 1 <=> 1;	// 0
echo 2 <=> 1;	// 1
  • 类型声明
/* 开启严格模式 */
delcare(strict_types=1); 
function test_declare(int $a) : int                       
{
    
    
   return $a * 2;
}
  • null合并符
$page = isset($_GET['page']) ? $_GET['page'] : 0;

/* 简化写法  */
$page = $_GET['page'] ?? 0;
  • 常量数组
define('ANIMALS', ['dog', 'cat', 'bird']);
  • namespace批量导入
use Space\{
    
    Class1, Class2, Class3};  
  • throwable接口
/* 1. 可以通过try catch捕获函数未定义错误 */
try {
    
    
	testFunc(); // 不要定义这个函数
} catch (Erro $e) {
    
    
	var_dump($e);
}
----------------------------------------------

/* 2. set_exception_handler()*/
15:04 debian@debian:blog $vim test.php 
set_exception_handler(
	function($e) {
    
    
		var_dump($e;
});
testFunc();
var_dump(111);

15:04 debian@debian:blog $php test.php 
object(Error)#2 (7) {
    
    
  ["message":protected]=>
  string(37) "Call to undefined function testFunc()"
  ["string":"Error":private]=>
  string(0) ""
  ["code":protected]=>
  int(0)
  ["file":protected]=>
  string(32) "/home/wwwroot/default/blog/test.php"
  ["line":protected]=>
  int(17)
  ["trace":"Error":private]=>
  array(0) {
    
    
  }
  ["previous":"Error":private]=>
  NULL
}
  • Closure:call()
  1 <?php
  2 
  3 class Test
  4 {
    
    
  5     private $num = 1;
  6 }
  7 
  8 $f = function() {
    
    
  9     return $this->num + 1;
 10 };
 11 
 12 echo $f->call(new Test) . "\n";
 13 
 14 
 15 ?>                                                                                                    
  • intdiv函数
1 <?php
2 
3 echo (15 / 4) . "\n";
4 echo (int)(15 / 4) . "\n";                                                                            
5 echo intdiv(15, 4) . "\n";
6
7 ?>

15:12 debian@debian:default $php test.php 
3.75
3
3
  • list的方括号写法
$arr = [1, 2, 3];
list($a, $b, $c) = $arr;

$arr = [1, 2, 3];
[$a, $b, $c] = $arr;
  • 抽象语法树(AST)
1 <?php
2 
3 ($a)['b'] = 1;
4 
5 var_dump($a);                                                                                         
6 
7 
8 ?>

15:28 debian@debian:default $php test.php 
array(1) {
    
    
  ["b"]=>
  int(1)
}

猜你喜欢

转载自blog.csdn.net/gripex/article/details/103803875