让一个做了10PHPer的妹子员告诉你PHP7 的新特性的使用

PHP7 的新特性大概浏览下,还是能在工作的效率上有很大益处的。

1,性能提升

这个我就不做测试了,哈哈

2,类型声明

class Student{ public function __construct()
{ $this->name = 'durban';
}
}
$student = new Student();function enroll(Student $student, array $classes){ foreach ($classes as $class) { echo "Enrolling " . $student->name . " in " . $class . "\n";
}
}// enroll("name", ["class 1", "class 2"]);// Fatal error: Uncaught TypeError: Argument 1 passed to enroll() must be an instance of Student, string given// enroll($student, "class"); // Fatal error: Uncaught TypeError: Argument 2 passed to enroll() must be of the type array, string givenenroll($student, array("class 1", "class 2"));function stringTest(string $string){ echo $string . "\n";
}
stringTest("a string");

3,可以声明严格类型校验模式 , 此声明必须第一个声明

declare (strict_types = 1);

4, 标量类型提示

function getTotal(float $a, float $b)
{ return $a + $b;
}
// getTotal('a', 2); //Argument 1 passed to getTotal() must be of the type float, string given,$total = getTotal(3, 2);echo $total . "\n";

5, 返回类型声明

function getSum(float $a, float $b): int
{
// return $a + $b; // Fatal error: Uncaught TypeError: Return value of getTotal() must be of the type integer, float returned return (int) ($a + $b); // truncate float like non-strict
}$sum = getSum(3, 6);echo $sum . "\n";

6, 错误处理

新的继承如下

|- Exception implements Throwable

|- …

|- Error implements Throwable

|- TypeError extends Error

|- ParseError extends Error

|- ArithmeticError extends Error

|- DivisionByZeroError extends ArithmeticError

|- AssertionError extends Error

try { // Code that may throw an Exception or Error.
} catch (Throwable $t) { // Executed only in PHP 7, will not match in PHP 5} catch (Exception $e) { // Executed only in PHP 5, will not be reached in PHP 7}

7, Null Coalesce Operator

$name = $firstName ?? "Guest";

等同于

if (!empty($firstName)) {
$name = $firstName;
} else {
$name = "Guest";
}

还可以像下面这样使用

$name = $firstName ?? $username ?? $placeholder ?? “Guest”;

8, Spaceship Operator

$compare = 2 <=> 1

等同于下面

2 < 1? return -12 = 1? return 02 > 1? return 1

9,Easy User-land CSPRNG: random_int and random_bytes.

$int = random_int(1, 2);
var_dump($int);
$bytes = random_bytes(5);
var_dump(bin2hex($bytes));

这些你都看懂了吗!这是我的一个技术交流群:“535686202”热烈欢迎大家加入学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值