I found the entry PHP OOP - toString not working but it does not address my issue as I believe I am calling the magic method properly...
Here is my code:
class Alerts {
public $message;
public $type;
public $output;
public function __construct($message_id)
{
include 'con.php';
$stmt = $conn->prepare(
'SELECT * FROM alerts WHERE id = :message_id');
$stmt->execute(array(':message_id' => $message_id));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$this->type = $row['type'];
$this->message = $row['message'];
}
}
public function __toString (){
$output ='';
$output .= "<div class='" . $this->type . "'><button class='close' data-dismiss='alert'></button>";
$output .= "<i class='fa fa-check-circle'></i> <strong>";
$output .= $this->message;
$output .= "</strong> </div>";
return $output;
}
}
It works if I call:
$message_id = 6;
$alert = new Alerts($message_id);
$output ='';
$output .= "<div class='" . $alert->type . "'><button class='close' data-dismiss='alert'></button>";
$output .= "<i class='fa fa-check-circle'></i> <strong>";
$output .= $alert->message;
$output .= "</strong> </div>";
on the page but not if I use:
$message_id = 6;
$alert = new Alerts($message_id);
echo $alert->output;
I am a newbie with PHP OOP so you help is greatly appreciated
__toString()method is automatically called when an object is used in the context of a string. Just doecho $alert;->output... No language I know uses that to invoketoString.$output, you must use$this->outputin the context of a method.