Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does question mark (?) before type declaration means in php (?int) [duplicate]

Tags:

php

php-7.2

I have seen this code in https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Console/Output/Output.php line number 40 they are using ?int.

public function __construct(?int $verbosity = self::VERBOSITY_NORMAL, bool $decorated = false, OutputFormatterInterface $formatter = null)     {         $this->verbosity = null === $verbosity ? self::VERBOSITY_NORMAL : $verbosity;         $this->formatter = $formatter ?: new OutputFormatter();         $this->formatter->setDecorated($decorated);     } 
like image 948
Jagadesha NH Avatar asked Mar 21 '18 10:03

Jagadesha NH


People also ask

What does the question mark mean in PHP?

operator. In PHP 7, the double question mark(??) operator known as Null Coalescing Operator. It returns its first operand if it exists and is not NULL; otherwise, it returns its second operand. It evaluates from left to right.

What is type declaration in PHP?

Type declarations can be added to function arguments, return values, and, as of PHP 7.4. 0, class properties. They ensure that the value is of the specified type at call time, otherwise a TypeError is thrown. Note: When overriding a parent method, the child's method must match any return type declaration on the parent.


1 Answers

It's called Nullable types.

Which defines ?int as either int or null.

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.

Example :

function nullOrInt(?int $arg){     var_dump($arg); }  nullOrInt(100); nullOrInt(null); 

function nullOrInt will accept both null and int.

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

like image 179
Ataur Rahman Avatar answered Sep 27 '22 15:09

Ataur Rahman