We know that the name needs to be a string and that an array of options can be passed.
This is how I like to write my code. In a clear and readable way with minimal comments.
This code works, but there are issues with it.
Do we want the name to potentially be an empty string?
What if different options are passed in?
Step 1
If you use PHPStan (a PHP static analysis tool), you won't get any errors until you test against level 6.
Then you'll get this error:
Function sayHello() has parameter $options with no value type specified in iterable type array.
Now, we can use a docblock to provide more information to PHPStan to describe the structure of the $options array and that it has strings for keys and boolean values.
/**
* @param array<string, bool> $options
*/
Although it's not erroring, we can add the $name parameter and declare it as a string.
This specified the name cannot be an empty string and the shape of the options array.
With this, we get these errors that weren't included before:
Parameter #1 $name of function sayHello expects non-empty-string, '' given.
Parameter #2 $options of function sayHello expects array{shout: bool}, array{shout2: true} given.
Parameter #2 $options of function sayHello expects array{shout: bool}, array{shout: 'banana'} given.
Here's the thing
While I like to write minimal, readable and "self-documenting" code and not overuse docblocks by adding them everywhere, I only add them and comments where needed and provide value, either to someone reading the code in the future or to tools like PHPStan that help me make the code better.
- Oliver
Was this interesting?
About me
I'm an Acquia-certified Drupal Triple Expert with 17
years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.