dougal85 wrote:1. Is it better to echo from objects, or return results/parameters and echo depending on them?
- if you have a class that is used often (but not always) should you make an instance of it inside objects when its needeD? or make an instance and pass it into objects? for example with a class for your mysql connections.
These are good questions I ask myself from time to time. My answer would be it depends...
Regarding question 1, for example, if you are retuning something like an HTML control that you probably aren't going to change after calling it much (for instance, the method handles all the aliasing and state functionality) you may want to just echo the HTML out. If you had a method for calculating the volume of a sphere, for example, you might want to return the value so you can format it accordingly. I guess the rule would be, if you ever conceive the notion of altering output before writing to buffer, you probably want to simply return the output value.
As for question 2, I would definitely only create an instance of a supporting object, if that object is to be essential to the new object. Otherwise, I would probably optionally pass the object as a parameter to the new object. You can do it by reference also if you want the new object to work on the passed object instead of it's own copy.
I wrote the follow sample class to illustrate.
<?php
class Page
{
var $data;
var $title;
function Page($title)
{
$this->title;
}
function setDataObject(& $data)
{
$this->data=& $data;
}
function body($bgcolor, $class, $marginheight, $marginwidth, $leftmargin, $topmargin, $onload)
{
$value = "<body bgcolor=\"$bgcolor\" class=\"$class\" marginheight=\"$marginheight\" ";
$value .= "marginwidth=\"$marginwidth\" leftmargin=\"$leftmargin\" ";
$value .= "topmargin=\"$topmargin\" onload=\"$onload\">";
return $value;
}
function Render()
{
echo "<html>";
echo ( !empty($this->title) ) ? "<title>{$this->title}</title>" : "";
if ( $this->isDataInitialed() ) {
$sql = "SELECT * FROM table";
$rows = $this->data->getRecords($sql);
echo "<meta name=\"keywords\" content=\"";
foreach ($rows as $row) {
echo " {$row['meta']}";
}
echo "\">";
}
echo $this->body("blue", "0", "0", "0", "0", "0", "alert('hello world!')");
/*** etc. ***/
}
function isDataInitialed()
{
return ( is_object($this->data) ) ? true : false;
}
}
?>
This class is basically worthless (I'm surprised I took the time to make it!) but it shows how you might pass your actual Data class to the Page class and not just a copy of it. This would allow you to work on the actual MySQL resource within the Data class for example.