Friday 12 January 2018

php method argument type hinting with question mark (?type)

Just a note to add to the previous answers - it must be
either null or have a value in the specified type i.e. - you
cannot just omit it - have a look at an example:


class="lang-php prettyprint-override">class TestClass {
public
function fetch(?array $extensions)
{
//...

}
}

Now if you
call


(new
TestClass)->fetch();

this will
throw




ArgumentCountError : Too few arguments to function fetch()
...



To make it work without
passing array of $extensions you'd have to call it with
null as
argument


(new
TestClass)->fetch(null);

It
works best in the situations, where you are passing argument initially set to
null to another method for processing
i.e.


class TestClass {
public function
fetch(array $extensions = null)
{
//...

$this->filter($extensions);
}
private function filter(?array
$extensions)
{
//...

}
}

Now you can call
the fetch method without the
argument


(new
TestClass)->fetch();

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...