php方法参数类型提示带问号(?type)

fab*_*b2s 16 php

我只是在方法类型提示中使用问号的PHP(symfony/laravel)代码感觉:

public function functionName(?int $arg = 0)
Run Code Online (Sandbox Code Playgroud)

在其他情况下,?类型不是最后一个,但我没有找到任何没有默认的类型.

问题是,我找不到任何关于此的信息,我查了一下:

和7.2一样,但由于代码只需要7.1,所以看起来很正常.

我也用谷歌搜索,并在这里搜索,但要么这没有记录或问号主题是打败搜索引擎.

所以我现在觉得有点愚蠢,如果有人能够在方法签名参数中对这个问号的含义进行启发,我真的很感激.

谢谢

小智 21

这是php7.1中的一个新功能

http://php.net/manual/en/migration71.new-features.php

问号表示类型提示参数(或返回值)也允许为空.

所以在你的例子中,$ arg可以是null或任何整数.


Seb*_*ski 10

只是添加到先前答案的注释-它必须是null或具有指定类型的值,即-您不能省略它-看一个示例:

class TestClass {

    public function fetch(?array $extensions)
    {
        //...
    }        
}
Run Code Online (Sandbox Code Playgroud)

现在如果你打电话

(new TestClass)->fetch();
Run Code Online (Sandbox Code Playgroud)

这会抛出

ArgumentCountError : 函数 fetch() 的参数太少......

要使其在不传递数组的情况下工作,$extensions您必须将其null作为参数调用

(new TestClass)->fetch(null);
Run Code Online (Sandbox Code Playgroud)

它在您将最初设置null为另一种处理方法的参数传递的情况下效果最佳,即

(new TestClass)->fetch(null);
Run Code Online (Sandbox Code Playgroud)

现在您可以在fetch没有参数的情况下调用该方法

class TestClass {

    public function fetch(array $extensions = null)
    {
        //...

        $this->filter($extensions);
    }

    private function filter(?array $extensions)
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 9

考虑以下函数:

<?php

function testFnc1(string $param)
{
    var_dump($param);
}

function testFnc2(string $param = 'some string')
{
    var_dump($param);
}
    
function testFnc3(string $param = null)
{
    var_dump($param);
}

function testFnc4(?string $param)
{
    var_dump($param);
}

function testFnc5(?string $param = 'some string')
{
    var_dump($param);
}


function testFnc6(?string $param = null)
{
    var_dump($param);
}
Run Code Online (Sandbox Code Playgroud)

现在我们用不同的值来测试函数。

芬尼卡 没有争论 无效的 '其他字符串'
1 致命错误 未捕获的 ArgumentCountError 致命错误未捕获类型错误:传递给 testFnc1() 的参数 1 必须是字符串类型,给定 null 字符串(0)“” string(12)“其他字符串”
2 string(11) “某个字符串” 致命错误未捕获类型错误:传递给 testFnc2() 的参数 1 必须是字符串类型,给定 null 字符串(0)“” string(12)“其他字符串”
3 无效的 无效的 字符串(0)“” string(12)“其他字符串”
4 致命错误 未捕获的 ArgumentCountError 无效的 字符串(0)“” string(12)“其他字符串”
5 string(11) “某个字符串” 无效的 字符串(0)“” string(12)“其他字符串”
6 无效的 无效的 字符串(0)“” string(12)“其他字符串”

testFnc3(string $param = null)注意以下之间和时间上的区别testFnc4(?string $param)

  1. 没有参数被传递
  2. 论点是null

您可以调用testFnc3(),但不能testFnc4()调用,因为它没有声明默认值

你必须打电话testFnc4(null)

所以testFnc4(?string $param)允许,但必须提供这样的参数$paramnull