views:

52

answers:

2

I have:

class A{

    public $name = 'A';
    public $B;

    public function B_into_A($b)
    {
        $this->B = $b;
    }
}

class B{

    public $name = 'B';
    public $A;

    public function new_A_into_B($a)
    {
        $this->A = new $a;
    }
}

$a = new A;
$b = new B;
$a->B_into_A($b);
$b->new_A_into_B('A');

Is this a good way to insert another class inside a "main" class at the beginning of the runtime? Should I use references?

(Background: I currently work on a MVC framework in which I have to handle many classes within some main classes e.g. bootstrapper, wrapper, modules, adapter etc.)

+2  A: 

Yes and No...

Your first function call was fine, I would just use a more standard name:

$a = new A;
$b = new B;
$a->setB($b); // B_into_A is a little bit of a whacky function name

Your second call, it doesn't really make sense to pass a string and then create the object (Unless you're looking for some sort of factory). If you want B to own A:

$b->new_A_into_B( new A );

public function new_A_into_B($a)
{
    $this->A = $a;
}

Again i don't like the name.. Id probably go with setA() there as well.

Galen
Yes, of course, I expected to have class::factory() as method name. I just took this lousy name to express clearly what I mean ;)thank you btw.
daemonfire300
+1  A: 

Passing an object instead of its class name makes sense because then it is easier for the garbage collector to guess when it is not needed anymore.

<?php

class A {
    public $B;
}

class B {
    public $A;
}

$a = new A;
$b = new B;

$a->B = $a;
$b->A = $b;

Furthermore, I'd try to get rid of the setter methods. In practice the only benefit they provide is to validate input. Since it's not the case here, I'd advise you to directly assign the classes.

You asked "Should I use references?". Actually all objects are passed by reference since PHP5. The only way to get an exact copy of them is to use the clone keyword.

By the way, you do not need to store the class name within each object. Just use get_class().

thank you for the "get_class()" function ;)
daemonfire300