PHP7.4新特性汇总-php教程

资源魔 36 0

PHP7.4 新特点

PHP7.4曾经公布了。又带来了一些新特点。能够让咱们的代码写的更少了。

1.属性增加限定类型

<?php
class User {
  public int $age;
  public string $name
}  
$user = new User();
$user->age = 10;
$user->name = "张三";
//error
$user->age = "zhang";//需求通报int

2. 箭头函数

这个特点根本上参考 Js 的 ES6 的语法。能够让咱们的代码写的更少。假如你的代码有 fn 这个函数。可能会抵触

<?php
$factor = 10;
$nums = array_map(fn($n)=>$n * $factor,[1,2,3]);//[10,20,30]
//以前的写法
$nums = array_map(function($num)use($factor){
  return $num * $factor;
},[1,2,3])

3. 无限前往类型协变与参数类型逆变

仅当应用主动加载时,才提供齐全协变 / 逆变支持。正在单个文件中,只能应用非轮回类型援用,由于一切类正在被援用以前都必需可用。

<?php
class A {}
class B extends A {}
class Producer {
    public function method(): A {}
}
class ChildProducer extends Producer {
    public function method(): B {}
}
?>

4. 数组解包

应用开展运算符... 解包数组。这个特点,应该又是从 js 那排汇过去的。看例子

<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];//['banana', 'orange', 'apple', 'pear', 'watermelon'];
//老的写法
$fruits = array_merge(['banana', 'orange'],$parts,['watermelon']);

5. 空兼并运算符赋值

<?php
$array['key'] ??= computeDefault();
// 老的写法
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}
?>

6. 数值文字分隔符

数字文字能够正在数字之间蕴含下划线。

<?php
6.674_083e-11; // float
299_792_458;   // decimal
0xCAFE_F00D;   // hexadecimal
0b0101_1111;   // binary
?>

7. 容许从 __toString () 抛出异样

如今容许从 __toString() 诱发异样,以往这会招致致命谬误,字符串转换中现有的可规复致命谬误已转换为 Error 异样。

8. Filter

新增 FILTER_VALIDATE_FLOAT

<?php
  filter_var(1.00,FILTER_VALIDATE_FLOAT);
filter.filters.validate

9. strip_tags 支持数组

<?php
  strip_tags($str,['p','a','div']);
//老的写法
strip_tags($str,"<p><a><div>");
烧毁的特点
1. 不显式括号的嵌套三元运算符
<?php
1 ? 2 : 3 ? 4 : 5;   // deprecated
(1 ? 2 : 3) ? 4 : 5; // ok
1 ? 2 : (3 ? 4 : 5); // ok
?>

面试的时分,终于不必担忧问你这个后果是啥了。其实消费中,各人也没有会这么写。

2. 花括号拜访数组索引

<?php
$arr = ["a"=>"111"];
$index = "a";
$arr{$index}//烧毁
$arr[$index];

说瞎话,仍是第一次见到,烧毁了,阐明各人没有会这么用。

3. real 以及 is_real 实数

<?php
  $num = "";
  $a = (real) $num;//烧毁
  $a = (float) $num;

4. parent 要害词正在没父类的类中应用

正在不父类的类中应用 parent 会呈现编译谬误。

<?php
  class Test{
  public function index() 
  {
    return parent::index();//编译谬误
  }
}

5. money_format 函数

money_format 被烧毁,应用 numberFormater 交换

6. 移除了的拓展

1.Firebird/Interbase
2.Recode
3.WDDX

以上就是PHP7.4新特点汇总的具体内容,更多请存眷资源魔其它相干文章!

标签: php开发教程 php开发资料 php开发自学 PHP7

抱歉,评论功能暂时关闭!