Sbpro
Sbpro

Reputation: 988

Object of class stdClass could not be converted to string - when returning object from function

This one has baffled me for a while. I try to return my $content (object), from my function and I get fatal error:

Object of class stdClass could not be converted to string

if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED))
{
    $content = json_decode($this->_revApiCall($url));
    var_dump( $content);
    return($content);
}

It was working fine, but then it started giving me this. If I remove the return($content) fatal error goes away.

Another thing to note is that the error reporting mentions always the same line for the error, although for testing purposes I have moved the code a bit. Could that be a cache issue - I don't know - other changes on the code are affecting the execution of the script.

Whatever the case,

return $content 

produces fatal error - on a line that no code exists and I am clueless for the moment.

Upvotes: 0

Views: 1617

Answers (1)

Sbpro
Sbpro

Reputation: 988

I found out what the problem was.

The above code is part of a Joomla module and resides inside the module's helper.php Class.

Everything up to that point is fine and nothing mysterious with what the $content is (is indeed an object - the one object I am expecting there) - and nothing related with where it comes from.

if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED))
{
    $content = json_decode($this->_revApiCall($url));
    var_dump( $content);
    return($content);
}

Then later on, I was calling that function to get the $content object, from inside my module's module.php

I was assigning the $content object to a variable named $content, like so:

$helper = new ModuleHelper($params);
$content = $helper->returnContentObject();

So far things look obvious. But this is where the issue was sitting.

And there was the issue - because $content is a "mystery" variable that is used by Joomla's module rendering engine - some more info can be found here: The mystery with the $content variable in Joomla modules.

And despite the fact my code was doing obvious things, there was a parallel procedure behind the scenes.

And yes, my error_reporting was always pointing me to that same line nearby my helper's method return $content code - and that was completely misleading.

Upvotes: 2

Related Questions