PHP 7.1新特性的汇总介绍(2)

<?php class Foo { public function bar(): void { } } class Foobar extends Foo { public function bar(): array { // Fatal error: Declaration of Foobar::bar() must be compatible with Foo::bar(): void } }

五、类常量属性设定

这个特性说起来比较简单,就是现在类中的常量支持使用 public、private 和 protected 修饰了:

<?php class Token { // 常量默认为 public const PUBLIC_CONST = 0; // 可以自定义常量的可见范围 private const PRIVATE_CONST = 0; protected const PROTECTED_CONST = 0; public const PUBLIC_CONST_TWO = 0; // 多个常量同时声明只能有一个属性 private const FOO = 1, BAR = 2; }

此外,接口(interface)中的常量只能是 public 属性:

<?php interface ICache { public const PUBLIC = 0; const IMPLICIT_PUBLIC = 1; }

为了应对变化,反射类的实现也相应的丰富了一下,增加了 getReflectionConstant 和 getReflectionConstants 两个方法用于获取常量的额外属性:

<?php class testClass { const TEST_CONST = 'test'; } $obj = new ReflectionClass( "testClass" ); $const = $obj->getReflectionConstant( "TEST_CONST" ); $consts = $obj->getReflectionConstants();

六、多条件 catch

在以往的 try ... catch 语句中,每个 catch 只能设定一个条件判断:

<?php try { // Some code... } catch (ExceptionType1 $e) { // 处理 ExceptionType1 } catch (ExceptionType2 $e) { // 处理 ExceptionType2 } catch (\Exception $e) { // ... }

新的实现中可以在一个 catch 中设置多个条件,相当于或的形式判断:

<?php try { // Some code... } catch (ExceptionType1 | ExceptionType2 $e) { // 对于 ExceptionType1 和 ExceptionType2 的处理 } catch (\Exception $e) { // ... }

对于异常的处理简化了一些。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用PHP7.1能有一定的帮助,如果有疑问大家可以留言交流。

附:源 RFC 地址

Nullable Types
Square bracket syntax for array destructuring assignment
Allow specifying keys in list()
Generalize support of negative string offsets
Void Return Type
Class constant visibility modifiers
Multi catch

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/355ddfb24f39b61a7fe86748c419e259.html