我創建了一個類,輸出frpm mySQL查詢並格式化並返回它。從一個類打印或返回輸出和打印一個函數之間的區別是什麼
這裏的類:
<?php
class sql_output_two_rows extends sql {
function __construct($sql) {
$this->sql = $sql;
$this->output = "";
parent::__construct($this->sql);
$this->output .= "<table class='tablenarrow bordered'>\n";
$this->output .= "<tr>\n";
for ($f = 0; $f < $this->num_fields; $f++) {
if($f%($this->num_fields/2) == 0){
$this->output .= "<tr>\n";
}
if($f>0 && $f%($this->num_fields/2) != (($this->num_fields/2) - 1) || $f == ($this->num_fields - 1)){
$this->output .= "<th style='border-radius:0px;'>".$this->field_name[$f]."</th>\n";
}else{
$this->output .= "<th>".$this->field_name[$f]."</th>\n";
}
if($f%($this->num_fields/2) == (($this->num_fields/2) - 1)){
$this->output .= "</tr>\n";
}
}
$this->output .="</tr>\n";
for ($r = 0; $r < $this->num_rows; $r++) {
for ($f = 0; $f < $this->num_fields; $f++) {
if($f%($this->num_fields/2) == 0){
$this->output .= "<tr style='background:#dbe1ef;'>\n";
}
$this->output .= "<td>\n";
if($this->row_array[$r][$f] == ""){
$this->row_array[$r][$f]=" ";
}
$this->output .= $this->row_array[$r][$f];
$this->output .= "</td>\n";
if($f%($this->num_fields/2) == (($this->num_fields/2) - 1)){
$this->output .= "</tr>\n";
}
}
$this->output .= "<tr>\n";
$this->output .= "<td colspan = '".($this->num_fields/2)."'>\n";
$this->output .= "<hr>\n";
$this->output .= "</td>\n";
$this->output .= "</tr>\n";
}
$this->output .= "</table>\n";
// print $this->output;
return($this->output);
}
}
?>
通知之類的最後兩行。
我已將註釋輸出的行註釋掉了。如果我取消註釋該行,那麼我稱該類如下:
new sql_output_two_rows("select * from accounts limit 10");
它打印出來就好了。
但是,如果我離開它,因爲它是,因此稱之爲:
$output = new sql_output_two_rows("select * from cameron.accounts limit 10");
print $output . "\n";
然後我收到以下錯誤:
Object of class sql_output_two_rows could not be converted to string
爲了克服這個問題,我不得不添加此功能到類:
public function __toString(){
return $this->output;
}
我的問題是這樣的:發生了什麼使一個工作 - 即當我從c打印拉斯 - 而其他不 - 即,當我返回輸出。
我希望我很清楚。
這正是我正在尋找的答案。我瞭解嘗試打印對象並遇到「對象類」錯誤的問題。我只是想弄清楚我試圖打印的對象是什麼。正如荷馬所說:「杜赫」。非常感謝答案。 – user1411284