Object and reference problem
| From: | SafeV | Date: | Wed, 17 Oct 2001 02:28:21 +0000 |
| Subject: | Object and reference problem | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-71290@lists.php.net to get a copy of this message | ||
Someone, have a go at this!
I have encountered a very troublesome problem, which I don't see how to solve in an elegant way, since PHP doesn't support method overloading.
Suppose my class is, kind of a tree, like:
class A {
var $children;
function A() {
$this->children = array();} // I want this to accept both objects and strings etc. // IE. mixed function add($child) {
$this->children[] = $child;} function printStuff() {
foreach ($this->children as $child) {
if (is_object($child))
$child->printStuff();
else
echo $child;
}
}
}
Now this is fine:
1 $obj1 = new A();
2 $obj2 = new A();
3 $obj1->add("Something");
4 $obj2->add(", something else");
5 $obj1->add($obj2);
6 $obj1->printStuff();
and prints out "something, something else"
But if I swap lines 4 and 5 it only prints out "something".
Obviously, the add method of $obj1 only receives a copy of $obj2, and
if I try to add something to $obj2 afterwards, even thought it's supposed to be hooked with $obj1, it will "disappear".
For objects only I could solve this with declaring add() like:
function add(&$child) {
$this->children[] = $child;} So it receives a reference of the object, but then I can't add a string (fatal error, cannot pass string as reference), or an integer or double, for that matter! And I really don't want to use different method names! I don't have full control over the reference stuff in PHP, does anyone know how I can fix this? Or a workaround? Thanx!