php - what is the difference between printing from a class or returning the output and printing from a function -
i've created class takes output frpm mysql query , formats , returns it.
here's class:
<?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"; ($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"; ($r = 0; $r < $this->num_rows; $r++) { ($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); } } ?>
notice last 2 lines of class.
i've commented out line prints output. if uncomment line, call class thus:
new sql_output_two_rows("select * accounts limit 10");
it prints out fine.
however, if leave is, , call thus:
$output = new sql_output_two_rows("select * cameron.accounts limit 10"); print $output . "\n";
then following error:
object of class sql_output_two_rows not converted string
to overcome this, have add functionality class:
public function __tostring(){ return $this->output; }
my question this: happening make 1 work - ie when print class - , other not - ie when return output.
i hope i'm clear enough.
instead of printing $output
should print $output->output
more semantic way write be:
$sqloutput = new sql_output_two_rows("select * accounts limit 10"); print $sqlouput->output;
the reason works because, written, $output contains reference object sql-ouput_two_rows has attribute of $output. in php access object attributes -> arrow. ie: $output->output
Comments
Post a Comment