将对象转换为数组 - 调用任何魔术方法? [英] Casting object to array - any magic method being called?

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

问题描述

我有一个 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() 在 Foo 中,但我正在寻找一些更本机"的 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天全站免登陆