铸造对象数组 - 被调用任何魔术方法? [英] Casting object to array - any magic method being called?

查看:122
本文介绍了铸造对象数组 - 被调用任何魔术方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Foo类的一个对象:

I have an object of class Foo:

class Foo extends Bar {
    protected $a;
    protected $b;
}

$obj = new Foo();

我想(和有)做的是施放此对象的数组,像这样:

What I want (and have) to do is cast this object to an array, like this:

$arr = (array)$obj;

是否有被称为此时任何魔法(或不是魔术:))方法?或者有没有其他的办法拦截呢?我知道我可以写一个简单的方法,例如: asArray()中富,但是我正在寻找一些更多的本土PHP的方式。

Is there any magic (or not magic :)) method that is being called at this moment? Or is there any other way to intercept it? I know I can write a simple method, eg. asArray() in Foo, but I'm looking for some more "native" PHP ways.

推荐答案

您可以有类实现 ArrayAccess接口 接口。这将让你像对待一个数组对象而无需进行转换,你会得到了各成员如何使用的完全控制。

You can have the class implement the ArrayAccess interface. This will allow you to treat the object like an array without casting and you get total control over how the members are used.

这篇关于铸造对象数组 - 被调用任何魔术方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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