Claude Grecea
Claude Grecea

Reputation: 543

__toString() must return a string value

Can someone tell me what I am doing wrong? This is my first time using __toString. I receiving the follwoing error: Catchable fatal error: Method users_class::__toString() must return a string value

This is my call to the object using Smarty:

 {assign var='udatas' value="$userObj->fetchUser(array('id'=>$ststres[ststval].to_id))"}

This is the object.

class users_class {

protected $users_class;

public function __toString() {

    return $this->users_class;
}
  public function fetchUser(array $conditions){
            $db = Core::getInstance();

            $sql = "SELECT * FROM ".USERS." WHERE ";
            $i=0;
            $params = array();
            //$where = array();
            foreach ($conditions as $column => $value) {
            if (preg_match('/^[a-z-.-_]+$/', $column)) {
                if($i!=0){
                    $sql .= " AND ";
                }
            $sql .= "$column = ?";
            $params[] = $value;
            $i++;

    }
   }            
            //$sql .= implode(' AND ', $where);
            //$sql .= " order by title asc";    
            $res = $db->dbh->prepare($sql);
            $res->execute(array_values($params));
            return $res->fetch(PDO::FETCH_ASSOC);               
}   
   }

Upvotes: 12

Views: 23243

Answers (3)

Pragnesh P
Pragnesh P

Reputation: 165

just replace with: return (string)$this->user_class;

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 157990

The error message ... must return a string value ... just means the return value of __toString() has to be a value of data type string. If $users_class in your example is not intended to be a string value, it has be to converted to a string before returning it.

But when reading the above example, it seems to me that the var $users_class may just not have been initialized yet. In this case change the method __toString() to :

public function __toString() {
    if(is_null($this->users_class)) {
        return 'NULL';
    }
    return $this->user_class;
}

To make the above code working, you'll need to make a change in the smarty code too. Remove the double quotes around the value of the value= attribute.

Upvotes: 16

Kevin Barnard
Kevin Barnard

Reputation: 99

You are using $res->fetch(PDO::FETCH_ASSOC) which will return any array. You are accessing the values as a standard object. You need to cast to a class, you might try using the PDO::FETCH_CLASS instead of the FETCH_ASSOC.

It's hard to say with the code that you have included.

Upvotes: 0

Related Questions