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
Sharing classes
Moderator: General Moderators
Re: Sharing classes
That's what extends is for 
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: Sharing classes
Of the three options:
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.
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;
}
}(#10850)
Re: Sharing classes
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
arborint wrote:Of the three options: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.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; } }
Good point