Following on from the previous theme I’ve picked out another of my favourite new things in PHP to talk about – general strictness. In current version of PHP there is no way to define the type of thing that a function will return or accept as a parameter – very different to most other languages.

There are quite a few cases where passing the wrong thing to a function can cause weird behaviour – imagine a search page where you accidentally passed the query string as the page number, you’d always get page one with no error message. With PHP 7 though you can specify the types

function get_results(string $query, int $page_number){
    // stuff
}

This will throw an exception (we’ll get to those) if the parameters are switched around when the function is called. It’s also possible to specify the type that is returned by the function

function get_results(string $query, int $page_number): array {
    // stuff
}

This is more for catching issues inside the function such as accidentally returning a string that the application will try and use as a number. One limitation seems to be that there is no way to specify the type within the array – I want to say that an array of SearchResult objects is being returned. This can be done in Java

public List<SearchResult> getResults(String query, int pageNumber){
    // stuff
}

Minor thing but still would be nice to have. One more to follow