Search code examples
phpvariablesdeclaration

Php variable declaration with an interrogation point before the type


In php, what is the difference between the two following variable declarations, both for procedural mode and inside a class:

  • string $str; // without ? before the type
  • ?string $str; // with ? before the type

Thank you for your lights


Solution

  • Variable $str can only be of type string:

    string $str;
    

    Variable $str can be of type string or null:

    ?string $str;