Mike wants to know: Why I type hint function parameters in PHP? What is it? What are the advantages?
Last week, Mike asked for help with some advanced SQL to build a more performant version of his code. During that exchange, he noticed that I was adding the data type next the parameter variable number in my functions, like this:
function get_hierarchichal_term_metadata( WP_Term $term, $meta_key ) { // code left out for brevity } function get_terms_ancestory_tree( $term_id, array $meta_keys ) { // code left out for brevity }
Notice in the parameter list of my function definition, I listed out the data types of $term
and $meta_keys
.
In this episode, we’ll talk about what type hinting (or type declaration) is. And then we’ll discuss how it improves your code by making it more:
- stable
- reliable
- readable
- predictable
In a nutshell, you are building your function to only accept datasets (values) that are of a specific type. That’s it. You made your code more strict by controlling what that function will accept.
Click here to read the PHP manual on function arguments.
-
Click here if you want to see the gist used in this episode.