Hammerbot
Hammerbot

Reputation: 16344

PHP typing and null values

there is a functionality in Java that allows me to pass null values to methods in parameters and also to return null values:

class Test {
    public List<String> method (String string) {
        return null;
    }

    public void otherMethod () {
        this.method(null);
    }
}

However, in PHP, the following does not work:

<?php

class SomeClass {

}

class Test {
    public function method (): SomeClass
    {
        return null;
    }
}

$test = new Test();

$test->method();

I can't pass null values to typed methods either:

class Test {
    public function method (SomeClass $obj)
    {
        // I can't pass null to this function either
    }
}

I find this very annoying, is there something I am missing? Or is it just how it works in PHP and there is nothing I can do?

Upvotes: 1

Views: 62

Answers (1)

Olivier De Meulder
Olivier De Meulder

Reputation: 2501

php7.1 allows nullable types by prefixing the type with a question mark ?. You can pass nullable parameters or define functions returning nullable types.

Documentation here.

Your example:

<?php
class SomeClass {
}
class Test {
    public function method (): ?SomeClass
    {
        return null;
    } }
$test = new Test();
$test->method();

or

class Test {
    public function method (?SomeClass $obj)
    {
        // pass null or a SomeClass object
    }
}

Upvotes: 2

Related Questions