Page 1 of 1

Sharing classes

Posted: Mon Nov 03, 2008 4:58 pm
by rbx
I would like to know your opinion about the following problem:

There are 2 classes, say we class A and class B. I need to use object of class A inside the class B. Most important for me is usability and flexibility of the code. For example I don't think that implementation like create objects A and B in the main program and then use object A inside class B as global variable is good practice. So two ways come to my mind - 1) pass the object A into the constructor of class B or 2) include class A definition in the file where class B is defined and create instance in the constructor of class B. What is the best implementing practice? Is there any other better solution?

Thanks

Re: Sharing classes

Posted: Mon Nov 03, 2008 5:07 pm
by infolock
That's what extends is for ;)

Re: Sharing classes

Posted: Mon Nov 03, 2008 7:06 pm
by Christopher
Of the three options:

Code: Select all

class A {
}
// inherit class
class B extends A {
    public function __construct() {
    }
}
// hard code class internally
class B {
    public function __construct() {
        $this->a = new A;
    }
}
// composite object
class B {
    public function __construct($a) {
        $this->a = $a;
    }
}
I would recommend doing the last one whenever possible because it allow polymorphism. Use the first two when hard coding the relationship is necessary or beneficial.

Re: Sharing classes

Posted: Mon Nov 03, 2008 7:12 pm
by rbx
I cannot use option one because there is no such relationship between the two classes. Actually I am usually using opt 3, just wanted to know if there is some better way. Thanks

Re: Sharing classes

Posted: Wed Nov 05, 2008 4:08 pm
by infolock
arborint wrote:Of the three options:

Code: Select all

class A {
}
// inherit class
class B extends A {
    public function __construct() {
    }
}
// hard code class internally
class B {
    public function __construct() {
        $this->a = new A;
    }
}
// composite object
class B {
    public function __construct($a) {
        $this->a = $a;
    }
}
I would recommend doing the last one whenever possible because it allow polymorphism. Use the first two when hard coding the relationship is necessary or beneficial.

Good point :oops: