我是不是遗漏了什么或者 PHP 5.x 中真的不支持通用对象类型提示?
我觉得很奇怪,支持提示数组,而提示对象却不受支持,至少不是开箱即用。
我想要这样的东西:
function foo(object $o)
正如我们所做的那样:
function foo(array $o)
可能的使用示例:对象集合类的方法。
解决方法:使用由所有类实现的接口(interface)“Object”或从通用类“Object”扩展所有类并编写如下内容:
function foo(Object $o)
嗯,那一点都不可爱。
使用 stdClass
作为类型提示不起作用:
Catchable fatal error: Argument 1 passed to c::add() must be an instance of stdClass, instance of b given
最佳答案
由于类型提示应该使客户端代码适应您的 API,因此您使用接受接口(interface)的解决方案似乎是正确的。
这样看:yourMethod(array $input)
给 yourMethod()
一个数组来使用,因此你知道 exactly which native functions适用并可由 yourMethod()
使用。
如果你像这样指定你的方法:yourSecondMethod(yourInterface $input)
你也会知道哪些方法可以应用于 $input
因为你知道/可以查找接口(interface) yourInterface
附带的规则集。
在您的情况下,接受任何对象似乎都是错误的,因为您无法知道在输入上使用哪些方法。示例:
function foo(Object $o) {
return $o->thisMethodMayOrMayNotExist();
}
(不暗示语法有效)
关于PHP 类型提示 : array supported, 对象不是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1547696/