2

I want to convert my class object to array. I have already asked a question about how to convert object to array.

Object to Array Conversion

But While doing this I was wondering if we can do something like this:

$arrObj = (array) $objectOfMyClass;

As I know it will convert object to array but if there is some user defined function in which I can control this behavior and allow few of the members to be passed as array keys.

For Exmaple lets Say I have a class:

class Property {
    private $x;
    protected $y;
    public $z;

    public function someFunction() {
        //some code
    }

    public function someFunction1() {
        //some code1
    }
}

$objArray = (array) (new Property());

echo '<pre>', print_r($objArray, true), '</pre>';

Output:

Array
(
    [Propertyx] => 
    [*y] => 
    [z] => 
)

But I dont want this output I want to alter this output and want output like this:

Array
(
    [z] => 
)

or

Array
(
    [y] => 
    [z] => 
)

So there must be some way through which I can call a user defined function when some one tried to type cast my class objects like this:

class Property {
    ....
    ....

    public function __toArray() {
        return <'only public or protected members'>
    }
}

When some one use following statement:

$objArray = (array) (new Property());

It should invoke __toArray method. Same like __toString.

If anyone knows any ways to do something like this please help me.

If there are any other solutions out there which may result into the same output would be really helpful.

Thanks in Advance.

2 Answers 2

2

Unfortunately there's no magic equivalent to __toString for array conversion. There have been a couple of proposals to add it over the years, as well as similar __toBool, __toFloat methods, but none of them have made much progress (e.g. https://wiki.php.net/rfc/object_cast_to_types)

Objects support implementing the ArrayAccess interface, which deals with treating them like arrays in other ways, but it doesn't provide a method for a full cast.

There are a couple of workarounds available:

get_object_vars

As already mentioned, public properties only can be converted using the get_object_vars method, e.g.

class Foo
{
    private $x = 1;
    protected $y = 2;
    public $z = 3;
}

print_r(get_object_vars(new Foo));

Array
(
    [z] => 3
)

JsonSerializable

The JsonSerializable interface allows you to apply custom logic to what happens when json_encode is called, which provides an improvement in that it allows you to include private or protected properties, or any other custom logic you have.

class Foo implements JsonSerializable
{
    private $x = 1;
    protected $y = 2;
    public $z = 3;

    public function jsonSerialize()
    {
        return get_object_vars($this);
    }
}

print_r(json_decode(json_encode(new Foo), true));

Array
(
    [x] => 1
    [y] => 2
    [z] => 3
)

The json_decode and json_encode calls in the above can of course be wrapped up in some simple syntactic sugar, such as

function toArray($obj)
{
    return json_decode(json_encode($obj), true);
}

print_r(toArray(new Foo));

None of this allows you to override what happens when you use array casting itself, however. Hopefully one day one of the proposals will be accepted, but until then these are the best options available.

Sign up to request clarification or add additional context in comments.

Comments

1

Use json_decode() and json_encode() to convert php object to array..

$obj = (object) array('1' => 'foo');
echo "<pre>"; print_r($obj);

Your $obj look like this:

stdClass Object
(
    [1] => foo
)

Now use this:

$array = json_decode(json_encode($obj),true);
echo "<pre>"; print_r($array);

This will give you array

Array
(
    [1] => foo
)

4 Comments

I don't want to convert object to array, I want to do it automatically like __toString magic method does for converting object to string.
sorry brother I don't know any other method @AshishAwasthi, but i'll let you know if i got something helpful for you,,,
another method is get_object_vars, and i don't think there is another way to do this...
I think you should read my question first before answering and should visit the link that I have mentioned in my question, Such answer are already available when we google, also I have asked about how to convert from object to array in the link question that I have mentioned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.