39

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);
    }
Arosha De Silva
  • 457
  • 8
  • 16
Jagadesha NH
  • 2,145
  • 2
  • 18
  • 33

1 Answers1

63

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

Ataur Rahman
  • 1,278
  • 12
  • 12
  • 1
    So... it's a weakly typed strong type? :D – geoidesic Mar 06 '20 at 19:25
  • @geoidesic omg you killed me with that one lmao – Kenth John Israel Mar 09 '20 at 08:43
  • 2
    Well, languages like C# or Java when asking for an object, allows to pass null, so you can get null pointer exceptions easily unless you verify every parameter on every function manually because they are passing a *pointer*. In PHP you have to ask explicitly that you want an object, or an object or null because PHP passes a *reference*. In that sense, the parameters seem more strongly typed to me, compared with those languages (besides the fact that PHP is not a statically typed language). – Dev_NIX Sep 24 '20 at 09:03
  • what version php will be support? – MrTo-Kane Apr 23 '21 at 08:07
  • 1
    @MrTo-Kane nullable type is introduced in PHP 7.1 – Ataur Rahman Apr 25 '21 at 09:22