Cannot pass null argument when using type hinting



PHP Snippet 1:

function foo(?Type $t) {
}

PHP Snippet 2:

$this->foo(new Type()); // ok
$this->foo(null); // ok
$this->foo(); // error

PHP Snippet 3:

function foo(Type $t = null) {

}

PHP Snippet 4:

function foo(?Type $t)
{

}

PHP Snippet 5:

function foo(Type $t = null) {

}

PHP Snippet 6:

interface FooInterface
{
    function bar();
}
class Foo implements FooInterface
{
    public function bar()
    {
        return 'i am an object';
    }
}
class NullFoo implements FooInterface
{
    public function bar()
    {
        return 'i am null (but you still can use my interface)';
    }
}

PHP Snippet 7:

function bar_my_foo(FooInterface $foo)
{
    if ($foo instanceof NullFoo) {
        // special handling of null values may go here
    }
    echo $foo->bar();
}

bar_my_foo(new NullFoo);

PHP Snippet 8:

function foo(Type|null $param) {
    var_dump($param);
}

foo(new Type()); // ok : object(Type)#1
foo(null);       // ok : NULL

PHP Snippet 9:

if (trim($tables) != '') 
{
 //code 
} 

PHP Snippet 10:

  public function custom_trim(?string $value)
  {
    return is_string($value) ? trim($value) : $value;
  }