php 7.2已正式发布,该版本具有新特性,功能和改进,可以让我们编写更好的代码。在这篇文章中,我将介绍一些php 7.2中最有趣的语言特性-参数类型声明。
推荐:《php7教程》
参数类型声明
从php 5开始,我们可以在函数的声明中指定预期要传递的参数类型。如果给定值的类型不正确,那么php将引发错误。参数类型声明(也称为类型提示)指定预期传递给函数或类方法的变量的类型。
来一个例子:
class myclass { public $var = 'hello world';}$myclass = new myclass;function test(myclass $myclass){ return $myclass->var;}echo test($myclass);
在这段代码中,测试函数需要myclass的一个实例。不正确的数据类型会导致以下致命错误:
fatal error: uncaught typeerror: argument 1 passed to test() must be an instance of myclass, string given, called in /app/index.php on line 12 and defined in /app/index.php:8
由于php 7.2 类型提示可以与对象数据类型一起使用,并且此改进允许将通用对象声明为函数或方法的参数。这里是一个例子:
class myclass { public $var = '';}class firstchild extends myclass { public $var = 'my name is jim';}class secondchild extends myclass { public $var = 'my name is john';}$firstchild = new firstchild;$secondchild = new secondchild;function test(object $arg) { return $arg->var;}echo test($firstchild);echo test($secondchild);
在这个例子中,我们调用了两次测试函数,每次调用都传递一个不同的对象。在以前的php版本中这是不可能的。
对象返回类型声明
如果参数类型声明指定函数参数的预期类型,则返回类型声明指定返回值的预期类型。
返回类型声明指定了函数预期返回的变量的类型。
从php 7.2开始,我们被允许为对象数据类型使用返回类型声明。这里是一个例子:
class myclass { public $var = 'hello world';}$myclass = new myclass;function test(myclass $arg) : object { return $arg;}echo test($myclass)->var;
以前的php版本会导致以下致命错误:
fatal error: uncaught typeerror: return value of test() must be an instance of object, instance of myclass returned in /app/index.php:10
当然,在php 7.2中,这个代码会回应'hello world'。
参数类型宽限声明
php目前不允许子类和它们的父类或接口之间的参数类型有任何差异。那是什么意思?
考虑下面的代码:
<?phpclass myclass { public function myfunction(array $myarray) { /* ... */ }}class mychildclass extends myclass { public function myfunction($myarray) { /* ... */ }}
这里我们省略了子类中的参数类型。在php 7.0中,此代码会产生以下警告:
warning: declaration of mychildclass::myfunction($myarray) should be compatible with myclass::myfunction(array $myarray) in %s on line 8
自php 7.2以来,我们被允许在不破坏任何代码的情况下省略子类中的类型。这个建议将允许我们升级类以在库中使用类型提示,而不需要更新所有的子类。
在列表语法中尾随逗号
数组中最后一项之后的尾随逗号是php中的有效语法,有时为了轻松附加新项目并避免由于缺少逗号而导致解析错误,鼓励使用它。自php 7.2起,我们被允许在 分组命名空间中使用尾随逗号。
请参阅列表语法中的尾随逗号以便更深入地查看此rfc和一些代码示例。
以上就是php7.2中的新功能(参数类型声明)的详细内容。
