Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Matthias Noback:
Duck-typing in PHP
Feb 27, 2017 @ 13:45:55

In this new post to his site Matthias Noback talks about a topic not normally discussed outside of languages that support it natively - duck typing.

For quite some time now the PHP community has becoming more and more professional. "More professional" in part means that we use more types in our PHP code. Though it took years to introduce more or less decent types in the programming language itself, it took some more time to really appreciate the fact that by adding parameter and return types to our code, we can verify its correctness in better ways than we could before. And although all the type checks still happen at runtime, it feels as if those type checks already happen at compile time, because our editor validates most of our code before actually running it.

[...] think that nowadays many PHP developers agree that silent type conversions is not something which is very useful, nor safe. But sometimes it's good to remember what's possible with PHP, due to it being a dynamic scripting language.

He goes on to give an example of the flexibility of PHP and how the most basic functionality usually provides the most "loose" level of abilities. He talks about type enforcement, limiting interfaces and the things PHP does natively to help keep it simpler instead. He then introduces the duck-typing-library package and what it offers to help you run validation against values to ensure they're correctness and type.

tagged: ducktype package example flexibility interface

Link: https://php-and-symfony.matthiasnoback.nl/2017/02/convenient-ducktyping-in-php/