Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__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);               
}   
   }
like image 399
Claude Grecea Avatar asked Dec 17 '12 23:12

Claude Grecea


2 Answers

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.

like image 111
hek2mgl Avatar answered Nov 13 '22 20:11

hek2mgl


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

like image 2
Pragnesh P Avatar answered Nov 13 '22 19:11

Pragnesh P