PHP7.2中的新功能(参数类型声明)

PHP7.2中的新功能(参数类型声明),第1张

PHP7.2中的新功能(参数类型声明) 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目前不允许子类和它们的父类或接口之间的参数类型有任何差异。那是什么意思?

考虑下面的代码:

<?php
class 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中的新功能(参数类型声明)的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/679798.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-20
下一篇 2022-04-20

发表评论

登录后才能评论

评论列表(0条)

保存