(何时)应该在PHP中使用类型提示? [英] (When) should I use type hinting in PHP?
问题描述
我不明白PHP作者添加类型提示的动机。我很高兴在它出现之前住。然后,因为它被添加到PHP 5,我开始指定类型无处不在。现在我认为这是一个坏主意,因为鸭式类型保证类之间的最小耦合,并利用代码模块化和重用。
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.
感觉像类型提示拆分语言变成2个方言:有些人以静态语言风格编写代码,带有提示,其他人坚持使用好的旧动态语言模型。还是不是全有或全无的情况?
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?
推荐答案
这不是关于静态和动态类型,php仍然是动态的。它是关于接口的合同。如果你知道一个函数需要一个数组作为其参数之一,在函数定义中强制它。我更喜欢快速失败,而不是错误的稍后在函数中。
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.
(还要注意,你不能指定类型提示bool,int,string,float,感觉在动态上下文。)
(Also note that you cant specify type hinting for bool, int, string, float, which makes sense in a dynamic context.)
这篇关于(何时)应该在PHP中使用类型提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!