Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

php - Casting object to array - any magic method being called?

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;

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No

There is no __toArray magic method in PHP. An enhancement proposal has been rejected in 2006 with the following answer:

[2006-08-20 11:12 UTC] helly@php.net

Why not simply have a method asArray() maybe even as par of an interface:

interface ArrayConversion { function asArray(); }

See, we have __toString as it is supported in language constructs like echo, print and other internal functions. But we decided against an autoconversion for arrays already. So itwill never be supported in any language construct. That said there is no needed for this and nothing you would win against the above interface. In fact you would make it php more complex because you'd add just one more magic feature.

It is thus very unlikely that it will be implemented in any future release (which is a pity, if you ask me).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...