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

reinisk22's avatar

How to cast an object to string

Hey,

I got an object like this:

MyApp\Match\MatchList {#78 ▼
  -platformId: "EUW1"
  -gameId: 4312601422
  -championId: 21
  -queueId: 420
  -season: 13
  -timestamp: 1575827032872
  -role: "DUO_CARRY"
  -lane: "BOTTOM"
}

But if I try to return it, I get an error like this:

The Response content must be a string or object implementing __toString(), "object" given.

This is how I get the object:

        foreach ($matchList['matches'] as $game){
            return new MatchList(
                $game['platformId'],
                $game['gameId'],
                $game['champion'],
                $game['queue'],
                $game['season'],
                $game['timestamp'],
                $game['role'],
                $game['lane'],
            );
        }

I tried to cast the object to string with (string), but it didnt work. I read about a __toString magic method, but I don't understand how I implement it in my MatchList class.

0 likes
6 replies
Nakov's avatar

@reinisk22 why do you immediately return from a loop? This means that just the first game will be returned.. Try returning JSON response instead then:

return response()->json(new MatchList(
                $game['platformId'],
                $game['gameId'],
                $game['champion'],
                $game['queue'],
                $game['season'],
                $game['timestamp'],
                $game['role'],
                $game['lane'],
            ));
reinisk22's avatar

@sinnbeck No, I save nothing in DB. I get this data from an API call. MatchList is basically a class with constructor, and a getter method for each property. Nothing else

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Well it would be quite easy to make some sot of __toString yourself

public function __toString() 
{
$data = [
'platformId' => $this->platformId,
'gameId' => $this->gameId,
...
];
return json_encode($data);
}
reinisk22's avatar

@nakov I just experiment, having a hard time getting what I need to work, thanks for advice tho!

laraveldev2019's avatar

In PHP approach, Example : of users table

$users = App\User::all();

$users = (string) $users;

dd($users);

Please or to participate in this conversation.