A good practice in most oo programming is to pass by reference when the object has a large construction cost (in speed or memory size), or when you want to reference an object (or variable) inside another object. The following explanation is not for the faint of heart....
For instance let's say I have a parent and child object. I want to child to be able to reference it's parent. I have the following code...
class CParent
{
var $text;
function CParent()
{
echo "CParent ctor entered<BR>";
$this->text = "EMPTY";
}
function setText($text)
{
$this->text = $text;
}
function getText()
{
return $this->text;
}
function dump()
{
$text = $this->text;
echo "text: [$text]<BR>";
}
}
class CChild
{
var $parent;
function CChild(&$parent)
{
echo "CChild ctor entered<BR>";
$this->parent = &$parent;
}
function dump()
{
$this->parent->dump();
}
}
//main code block
$parent = new CParent();
$child = new CChild($parent);
$child->dump();
/ this will print:
text: [EMPTY]
/
$parent->setText("Child won't see me");
$parent->dump();
/ this will print:
text: [Child won't see me]
/
$child->dump();
/ this will print:
text: [EMPTY]
*/
To fix this problem all we have to do is change the constructor for CChild from:
function CChild($parent)
{
echo "CChild ctor entered<BR>";
$this->parent = $parent;
}
to:
// added an &
function CChild(&$parent)
{
echo "CChild ctor entered<BR>";
// added an &
$this->parent = &$parent;
}
Note: The reference symbol (&) has been added both to the constructor function parameter list and to the assignment of the member variable to the variable passed in.
now the code produces this result:
//main code block
$parent = new CParent();
$child = new CChild($parent);
$child->dump();
/ this will print:
text: [EMPTY]
/
$parent->setText("Child won't see me");
$parent->dump();
/ this will print:
text: [Child won't see me]
/
$child->dump();
/ this will print:
text: [Child won't see me]
/
voila, now $child correctly refers to the real parent object. Try it. It might work, too 🙂
ps. If anyone else is venturing into real OO development in php, shoot me off an email. That is, if you know what a GOF design pattern is.
Larry