简体   繁体   English

PHP输入和空值

[英]PHP typing and null values

there is a functionality in Java that allows me to pass null values to methods in parameters and also to return null values: Java中有一项功能,它允许我将空值传递给参数中的方法并返回空值:

class Test {
    public List<String> method (String string) {
        return null;
    }

    public void otherMethod () {
        this.method(null);
    }
}

However, in PHP, the following does not work: 但是,在PHP中,以下操作无效:

<?php

class SomeClass {

}

class Test {
    public function method (): SomeClass
    {
        return null;
    }
}

$test = new Test();

$test->method();

I can't pass null values to typed methods either: 我也不能将null值传递给类型化方法:

class Test {
    public function method (SomeClass $obj)
    {
        // I can't pass null to this function either
    }
}

I find this very annoying, is there something I am missing? 我觉得这很烦人,我缺少什么吗? Or is it just how it works in PHP and there is nothing I can do? 还是只是它在PHP中的工作方式,我无能为力?

php7.1 allows nullable types by prefixing the type with a question mark ? php7.1通过在类型前面加上问号来允许可空类型? . You can pass nullable parameters or define functions returning nullable types. 您可以传递可为空的参数,也可以定义返回可为空的类型的函数。

Documentation here. 这里的文档。

Your example: 你的例子:

<?php
class SomeClass {
}
class Test {
    public function method (): ?SomeClass
    {
        return null;
    } }
$test = new Test();
$test->method();

or 要么

class Test {
    public function method (?SomeClass $obj)
    {
        // pass null or a SomeClass object
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM