Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(When) should I use type hinting in PHP?

Tags:

I can't understand the motivation of PHP authors to add the type hinting. I happily lived before it appeared. Then, as it was added to PHP 5, I started specifying types everywhere. Now I think it's a bad idea, as far as duck typing assures minimal coupling between the classes, and leverages the code modularization and reuse.

It feels like type hints split the language into 2 dialects: some people write the code in static-language style, with the hints, and others stick to the good old dynamic language model. Or is it not "all or nothing" situation? Should I somehow mix those two styles, when appropriate?

like image 638
Ivan Krechetov Avatar asked Feb 11 '09 12:02

Ivan Krechetov


People also ask

Should I use type hinting in PHP?

With Type hinting we can specify the expected data type (arrays, objects, interface, etc.) for an argument in a function declaration. This practice can be most advantageous because it results in better code organization and improved error messages.

What are reasons for using type hinting?

PEP 484 introduced type hints — a way to make Python feel statically typed. While type hints can help structure your projects better, they are just that — hints — and by default do not affect the runtime.

What is PHP type hinting?

In simple word, type hinting means providing hints to function to only accept the given data type. In technical word we can say that Type Hinting is method by which we can force function to accept the desired data type. In PHP, we can use type hinting for Object, Array and callable data type.

When was type hinting added PHP?

In May of 2010 support for scalar type hinting was added to the PHP trunk.


1 Answers

It's not about static vs dynamic typing, php is still dynamic. It's about contracts for interfaces. If you know a function requires an array as one of its parameters, force it right there in the function definition. I prefer to fail fast, rather than erroring later down in the function.

(Also note that you cant specify type hinting for bool, int, string, float, which makes sense in a dynamic context.)

like image 58
Mario Avatar answered Oct 12 '22 23:10

Mario