Home > Mobile >  PHP type hint none
PHP type hint none

Time:08-19

I've build iterator in PHP which has a method that returns an array property when iterator is not valid:

class MyIterator... {

    private array $arrayProperty = [];

    public function returnArray():array {

        // Appending values to that array
        // next,current stuff...

        if (! $this->valid()){
            return $this->arrayProperty
    }
}

Everything worked fine until I've typehinted return type array. Now im getting TypeError: Return value must be of type array, none returned. is there a way how to type hint none?

CodePudding user response:

I will presume the code is this:

public function returnArray():array {

    // Appending values to that array
    // next,current stuff...

    if (! $this->valid()){
        return $this->arrayProperty;
    }
}

In this case, indeed you are returning nothing. Typehint so and make it explicit:

public function returnArray(): ?array {

    // Appending values to that array
    // next,current stuff...

    if (! $this->valid()){
        return $this->arrayProperty;
    }
    return NULL;
}

CodePudding user response:

In PHP, any function that doesn't explicitly return a value implicitly returns null. Consider the following:

function a() {
    // do nothing
}
var_dump( a() ); // null

function b($condition) {
    if ( $condition ) {
       return 42;
    }
}
var_dump( b(true) ); // int(42)
var_dump( b(false) ); // null

So your function returns either an array or null, which can be declared with a nullable type: ?array

For clarity, you might want to explicitly write out the return null

class MyIterator... {

    private array $arrayProperty = [];

    public function returnArray(): ?array {

        // Appending values to that array
        // next,current stuff...

        if (! $this->valid()){
            return $this->arrayProperty;
        }
        else {
            return null;
        }
    }
}
  • Related