我创建了一个类,它接受输出 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;
}
我的问题是:使一个工作发生了什么——即当我从课堂上打印时——而另一个不工作——即当我返回输出时。
我希望我足够清楚。