2

I found out a php file inside which it had a function like below:

public function getCharset(): ?string
{
    return $this->charset;
}

I want to know what is : ?string doing here.

Surya Neupane
  • 906
  • 10
  • 20
  • Does this answer your question? [What is the purpose of the question marks before type declaration in PHP7 (?string or ?int)?](https://stackoverflow.com/questions/48450739/what-is-the-purpose-of-the-question-marks-before-type-declaration-in-php7-stri) – Syscall Jan 30 '22 at 08:59

1 Answers1

6

This is known as a nullable type, and is introduced in PHP 7.1:

Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, NULL can be passed as an argument, or returned as a value, respectively.

Essentially, the function can return either the specified type or null. If it would return a different type, an error is thrown:

function answer(): ?int  {
    return null; // ok
}

function answer(): ?int  {
    return 42; // ok
}

function answer(): ?int {
    return new stdclass(); // error
}
Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71