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);
}
}
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.
just replace with: return (string)$this->user_class;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With