Object to array conversion oddity



A simple class like this:

class Myclass() {
public $field1 = '';
private $field2 = '';
public function __sleep() {
return array('field1', 'field2');
}
}
$myclass = new Myclass;

If I var_dump this, I get:

object(Myclass)#6 (2) {
["field1"]=>
string(0) ""
["field2:private"]=>
string(0) ""
}

If I coerce this to an array:

$arr = (array)$myclass;

the properties change names in a most unhelpful way:

array(2) {
["field1"]=>
string(0) ""
["Myclassfield2"]=>
string(0) ""
}

The docs (http://www.php.net/manual/en/language.types.array.php) say:

"If you convert an object to an array, you get the properties (member variables) of that object as the array's elements. The keys are the member variable names."

It seems that's not quite true.

How can I stop it doing this? Looks a bit buggy to me.

Marcus
--
Marcus Bointon
Synchromedia Limited: Creators of http://www.smartmessages.net/
marcus@xxxxxxxxxxxxxxxxxx | http://www.synchromedia.co.uk/
.



Relevant Pages

  • Re: Is it good programming to set instance in class without using C-tor
    ... I have a class definition called MyClass see below. ... I create an instance of this class MyClass ... the question of what arguments should go on the constructor is ... your client has to test before they try to use an object instance. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Object creation overhead
    ... > class MyClass ... This is, of course, over and above the memory required for the ... > 'MyClass' objects themselves. ... > The 'proxy' class approach won't see a reduction in the number of ...
    (comp.lang.java)
  • Re: Class instancing
    ... > Public Function CreateClass() As MyClass ... > Set CreateClass = New MyClass ...
    (microsoft.public.access.modulesdaovba)
  • Re: Changed class
    ... public int value1=0; ... private int oldvalue1=0; ... MyClass nn = new MyClass ... Class MyClass {public int value1=0; ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: super.clone() puzzlement
    ... public class MyClass { ... public MyClass(MyClass mine) { ... That is, I want a copy of the MyClass instance where, when I change the object referenced by its value, a copy I've made of the MyClass instance keeps its own value object intact. ... public MyClass(T value, ValueCopier<T> copier) { ...
    (comp.lang.java.programmer)

Loading