簡體   English   中英

PHP7中類型聲明前的問號(?string或?int)的目的是什么?

[英]What is the purpose of the question marks before type declaration in PHP7 (?string or ?int)?

你能告訴我這叫什么嗎? ?stringstring

用法示例:

public function (?string $parameter1, string $parameter2) {}

我想了解一些關於它們的信息,但在 PHP 文檔和谷歌中都找不到它們。 它們之間有什么區別?

它被稱為Nullable 類型,在 PHP 7.1 中引入。

如果存在 Nullable 類型(帶有? )參數或相同類型的值,則可以傳遞NULL值。

參數:

function test(?string $parameter1, string $parameter2) {
        var_dump($parameter1, $parameter2);
}

test("foo","bar");
test(null,"foo");
test("foo",null); // Uncaught TypeError: Argument 2 passed to test() must be of the type string, null given,

返回類型:

函數的返回類型也可以是可空類型,並允許返回null或指定類型。

function error_func():int {
    return null ; // Uncaught TypeError: Return value must be of the type integer
}

function valid_func():?int {
    return null ; // OK
}

function valid_int_func():?int {
    return 2 ; // OK
}

屬性類型(自 PHP 7.4 起):

屬性的類型可以是可為空的類型。

class Foo
{
    private object $foo = null; // ERROR : cannot be null
    private ?object $bar = null; // OK : can be null (nullable type)
    private object $baz; // OK : uninitialized value
}

另見:

可空聯合類型(自 PHP 8.0 起)

從 PHP 8 開始, ?T表示法被認為是T|null常見情況的簡寫”

class Foo
{
    private ?object $bar = null; // as of PHP 7.1+
    private object|null $baz = null; // as of PHP 8.0
}

錯誤

如果運行的PHP版本低於PHP 7.1,則拋出語法錯誤:

語法錯誤,意外的“?”,需要變量(T_VARIABLE)

? 運營商應該被刪除。

PHP 7.1+

function foo(?int $value) { }

PHP 7.0 或更低

/** 
 * @var int|null 
 */
function foo($value) { }

參考文獻

PHP 7.1 開始

現在可以通過在類型名稱前加上問號將參數和返回值的類型聲明標記為可為空。 這表示 NULL 和指定的類型一樣,可以分別作為參數傳遞或作為值返回。

PHP 7.4 起:類屬性類型聲明。

PHP 8.0 起:可空聯合類型

函數參數中string前的問號表示可空類型 在上面的示例中,必須允許$parameter1具有NULL值,而$parameter2則不允許; 它必須包含一個有效的字符串。

具有可為空類型的參數沒有默認值。 如果省略該值不會默認為 null 並且會導致錯誤:

函數 f(?callable $p) { }
f(); // 無效; 函數 f 沒有默認值

這意味着允許參數作為指定類型或 NULL 傳遞:

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

這大致相當於

 public function (string $parameter1 = null, string $parameter2) {}

只不過還是需要參數,省略參數會報錯。

特別是在這種情況下,第二個參數是必需的,使用=null會使第一個參數成為可選的,這實際上不起作用。 當然它可以工作,但我的意思是它實際上並沒有使它成為可選的,這是默認值的主要目的。

所以使用

public function (?string $parameter1, string $parameter2) {}

在這種情況下,語法上更有意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM