The empty value

?? and ?Type differ: one is about reading, the other about the signature.

?string means "a string or null". That is how you mark a field that may be absent. Without the question mark, string $name = null does not pass in modern PHP. A return type of ?User means "found or not", and the caller must check for null before the -> arrow.

The ?-> operator does not call a method on null; it returns null. That is shorter than a ladder of ifs. A chain like $user?->city?->name is handy until you forget to replace the final null with an answer. For the client, the string none is better than a raw null in a random place of the JSON.

?? substitutes a fallback if the left side is null or the key is missing. It does not replace an empty string. An empty name and a missing name are different cases. An empty name is often a validation error; a missing one gets a default value.

Do not smear null across the whole service as "one more type just in case". At the boundary, turn it into a domain value: no city means the string none or a separate result. From then on the code works with a string and does not check for null in every paragraph.

Practice

  1. What ?string means

    Which values does an argument of type ?string accept?

    • only null
    • a string or null
    • any type
    • only an empty string
  2. A fallback value

    What string does the expression null ?? 'none' give?

  3. A city or none

    Write function city_or_none($map, $name). Return the key's value or none, never a warning.