Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ChrisF79's avatar

Can't turn an object into an array.

Just starting to work on something and I have the following code:

class ProcessRetsListings
{

    public function __construct($results)
    {
        $this->results = $results;
    }

    public function process($results)
    {
        $results->toArray();
        foreach ($results as $result)
        {
            echo $result['StreetName'];
        }
    }
}

I ran a php gettype($results) and it is in fact an object. I try to turn it into an array and I get the error: Call to undefined method App\Models\RetsFeedApiResult::toArray()

I need it to be an array so I can work with it and ultimately save the entire result to the database.

0 likes
8 replies
Cronix's avatar

->toArray() only works on certain laravel objects, like models, not php objects in general.

You could try just typecasting it to an array, but you'd only get visible (public) properties.

$results = (array) $results;
jimmck's avatar

This object has private, protected or public data members only a constructor which takes an array and a method to iterate the array.

spekkionu's avatar

What does the RetsFeedApiResult class look like? Unless it is a simple object with public properties you will likely have to write your own toArray method.

Snapey's avatar

I need it to be an array so I can work with it

Why? Just because that is familar? PHP works very well with objects

ChrisF79's avatar

Thanks everyone. @Snapey, main reason is because I think I can just insert it right into the DB.

jlrdw's avatar

It is just


$whatever = $row->whatever;

// Instead of

$whatever = $row->['whatever'];
Snapey's avatar

The class would need to implement a toArray() method, but I'm guessing you cannot modify it?

Please or to participate in this conversation.