Jump to content

[SOLVED] Class could not be converted to string


XpertWorlock

Recommended Posts

Having a problem with a class, doesn't happen offline, but seems to occur when uploaded.

 

PHP offline 5.3

PHP online 5.2.9

 

Class code

class newsArticle{

function setDate($a){$this->date = unixToGregorian('j',$a);}
function setTitle($a){$this->title = $a;}
function setAuthor($a){$this->author = $a;}
function setDescription($a){$this->description = $a;}
function setID($a){$this->id = $a;}
}

 

calling of Class newsArticle

$news[$i] = new newsArticle();
	$news[$i]->setDate($row['date'] - (3600*5)); 
	$news[$i]->setTitle(mysql_real_escape_string($row['title']));
	$news[$i]->setAuthor($row['author']);
	$news[$i]->setDescription(mysql_real_escape_string($row['description']));
	$news[$i]->setID($row['id']);
	$i++;

 

 

The error I get is

 

Catchable fatal error: Object of class newsArticle could not be converted to string in ......

That error generally only occurs when you try to use the instance of the class as though it was a string, such as -

 

echo $news[$i];

 

Are you sure about the line where the error is occurring? Any chance that $i is an instance of a class?

 

Your posted code does not produce any php error under php5.2.11 (I don't have php5.2.9 to test with.)

If you do want to use an instance of a class like a string it's useful to utilize the __toString() magic method. Ex:

 

class someClass
{
     public function __toString()
     {
          return 'Some name';
     }
}

$in = new someClass;
echo $in; // Some name

if(mysql_num_rows($result) > 0)

{

$i=1;

while($row = mysql_fetch_array($result))

{

$news[$i] = new newsArticle();

$news[$i]->setDate($row['date'] - (3600*5)); //SET TO 5, WILL HAVE TO CONFIGURE

$news[$i]->setTitle(mysql_real_escape_string($row['title']));

$news[$i]->setAuthor($row['author']);

$news[$i]->setDescription(mysql_real_escape_string($row['description']));

$news[$i]->setID($row['id']);

$i++;

}

}

 

 

The $i is just to go through an array.  Like I said it works perfectly offline, doesn't want to work online though

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.