所有动态语言都支持鸭子类型吗?
所有动态语言都支持鸭子打字吗?
我认为 PHP 支持鸭子类型。是这样吗?
Do all dynamic languages support duck typing?
I would think that PHP supports duck typing. Is that the case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
任何动态类型的 oop 语言都支持鸭子类型,包括 php。
这不是一个功能,而是编程风格。
Any dynamically-typed oop language supports duck-typing, including php.
It's not a feature, it's rather programming style.
静态类型意味着一旦定义了变量,它在其生命周期内将保持相同的类型。静态语言通常要求您声明类型,但有些语言具有类型推断——它们将从定义中推断出类型。例如,在 scala 中,您可以编写
i = 1
,编译器将推断i
的类型为int
,但您可以'然后声明i = "1"
,这将引发错误。动态类型意味着您不必声明变量的类型,并且可以更改变量的类型。在ruby中,你可以在
i = 1
后面加上i = "1"
,完全没有问题。鸭子类型是一个不同的概念,几乎只适用于面向对象的语言。在使用 Duck 类型的语言中,不会检查方法参数的类型,因此您传递给该方法的任何类型都是可接受的,只要它响应它收到的任何调用。
因此,例如:
quacker 方法将采用 Duck 或 FauxDuck,因为两者都会响应
.quacks
虽然大多数面向对象的动态类型语言也是鸭子类型,但这不是必需的。您可以使用一种语言来声明方法调用的类型并强制执行它们,但仍然是动态类型的 - 请记住,动态类型只是意味着您可以在定义对象后更改它的类型。
在假设的非鸭子类型的 ruby 中,
我不知道为什么要这样做,但这是语言设计者可以选择的。
Static typing means that once you have defined a variable, it stays the same type for its lifetime. Static languages usually require that you declare the type, but some have type inference--they will infer the type from the definition. In scala, for example, you can write
i = 1
and the compiler will infer the type ofi
to beint
, but you can't then declarei = "1"
, that will throw an error.Dynamic typing means that you don't have to declare the type of a variable and you can change the type of a variable. In ruby, you can follow
i = 1
withi = "1"
and there is no problem at all.Duck typing is a different concept that applies almost exclusively to object oriented languages. In a language with Duck typing, arguments to a method are not checked for type, so any type that you pass into the method is acceptable as long as it responds to any calls it receives.
So, for example:
The method quacker will take either a Duck or a FauxDuck, because either will respond to
.quacks
While most object-oriented dynamically typed languages are also duck typed, it isn't a requirement. You could have a language that declared types to method calls and enforced them, but was still dynamically typed--remember, dynamic typing just means that you can change the type of an object after you've defined it.
In hypothetical non-duck typed ruby
Why you would want to do this, I don't know, but it's a choice available to language designers.
是的,PHP 是一种鸭子类型的语言。
Yes, PHP is a duck-typed language.