1

I ran into a code in PHP, which has strange question mark operators. Since the code itself doesn't have any comments on that part, i tried to google it, but failed to succeed.

The code i'm interested in goes like:

<?php
class Cart
{
    private $_user;
    private $_items = [];
    public function __construct(?User $user)
    {
        $this->_user = $user;
    }
    public function getUser(): ?User
    {
        return $this->_user;
    }

My first thought was of type hinting, which was introduced in PHP 7, but it's apparently not the case, nor it is the strict type declaration. I've got no idea, what it is. Can you help me?

tnsaturday
  • 527
  • 2
  • 10
  • 31

2 Answers2

2

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

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.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
1

This means your parameter or return can be null.

PHP 7.1 introduced it : http://php.net/manual/en/migration71.new-features.php

Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84