类型提示:默认参数 [英] Type Hinting: Default Parameters

查看:157
本文介绍了类型提示:默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 5类型提示

PHP 5引入了类型提示. 函数现在可以通过在函数中指定类的名称来将参数强制为对象( 原型 )或arrays( 自PHP 5.1 起).但是,如果将NULL用作默认参数值,则以后的任何调用都将其用作参数.

PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

以上摘录的以下内容:

The following excerpt from the above:

如果将NULL用作默认参数值,则以后的任何调用都将其用作参数.

if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

是不是上面的意思:

如果要将默认参数与类型提示一起使用,则只能将 NULL 作为默认值.

if default parameters are to used use with type hinting, it can have only have NULL as the default value.

.代码1中的代码错误并导致:

i.e. the code in code1 is wrong and results in:

致命错误:带有类类型提示的参数的默认值只能为NULL

 function setName ( string $name = "happ") {
  ...
  }

其中code2中的代码正确:

Where as code in code2 is right:

 function setName ( string $name = NULL) {
  ...
  }

为什么要在php中分配此约束?

Why is this constraint assigned in php?

推荐答案

您不能键入提示字符串,只能键入提示对象和数组,所以这是不正确的:

You can't typehint strings, you can only typehint objects and arrays, so this is incorrect:

function setName ( string $name = "happ") {

(在这里没有得到编译时错误的原因是因为PHP将字符串"解释为类的名称.)

(The reason you don't get a compile-time error here is because PHP is interpreting "string" as the name of a class.)

文档中的措辞意味着,如果您这样做:

The wording in the docs means that if you do this:

function foo(Foo $arg) {

然后,传递给foo()的参数必须是对象Foo的实例.但是,如果您这样做:

Then the argument passed to foo() must be an instance of object Foo. But if you do this:

function foo(Foo $arg = null) {

然后,传递给foo()的参数可以是对象Foo的实例,也可以为null.另请注意,如果您这样做:

Then the argument passed to foo() can either be an instance of object Foo, or null. Note also that if you do this:

function foo(array $foo = array(1, 2, 3))

那么您不能调用foo(null).如果需要此功能,可以执行以下操作:

Then you can't call foo(null). If you want this functionality, you can do something like this:

function foo(array $foo = null) {
    if ($foo === null) {
        $foo = array(1, 2, 3);
    }

[Edit 1] 从PHP 5.4开始,您可以键入提示callable:

function foo(callable $callback) {
    call_user_func($callback);
}

[Edit 2] 从PHP 7.0起,您可以键入提示boolfloatintstring.这使问题中的代码成为有效的语法.从PHP 7.1开始,您可以键入提示iterable.

As of PHP 7.0, you can typehint bool, float, int, and string. This makes the code in the question valid syntax. As of PHP 7.1, you can typehint iterable.

这篇关于类型提示:默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆