PHP类型提示:支持数组,不是对象吗? [英] PHP Type Hinting: array supported, object NOT?

查看:71
本文介绍了PHP类型提示:支持数组,不是对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否缺少某些东西,或者PHP 5.x中确实不支持通用对象类型提示?

Am I missing something or there really is no support for generic object type hinting in PHP 5.x?

我发现支持提示数组而提示对象不支持(至少不是开箱即用)确实很奇怪.

I find it really strange that hinting arrays is supported while hinting objects is not, at least not out of the box.

我想要这样的东西:

function foo(object $o)

就像我们一样:

function foo(array $o)

可能的使用示例:对象集合类的方法.

Example of possible use: methods of an objects collection class.

解决方法:使用由所有类实现的接口对象",或从通用类对象"扩展所有类,并编写如下内容:

Workaround: using an interface "Object" implemented by all classes or extending all classes from a generic class "Object" and writing something like this:

function foo(Object $o)

好吧,那不是很可爱.

使用stdClass作为类型提示不起作用:

Using stdClass as the type hint doesn't work:

可捕获的致命错误:参数1 传递给c :: add()的必须是一个实例 stdClass的实例,给出b的实例

Catchable fatal error: Argument 1 passed to c::add() must be an instance of stdClass, instance of b given

推荐答案

否,无法完成.我什么都没错过.

No, it can't be done. I wasn't missing anything.

这篇关于PHP类型提示:支持数组,不是对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆