1

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?

1 Answer 1

2

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.