Calling a child object in the parent object
I want to know if I can create a child object in a parent object an use it...
- I mean is it posible?
- Is it a good idea?
- What do I have to care if I do so?
I am using the child classes on their own and i want to use them in a private functio开发者_高级运维n of the parent class as well.
thanks
here some source to imagine what I am meaning:
class A{
private $child_class1;
private $child_class2;
private function somefunction(){
$this->child_class1 = new B();
$this->child_class1->do_something();
$this->child_class2 = new C();
$this->child_class2->do_something();
}
}
class B extends A{
public function do_something(){
...
}
}
class C extends A{
public function do_something(){
...
}
}
You could use abstract methods to delegate certain actions to derived classes:
class A {
public function __construct() {
$this->do_something();
}
protected abstract function do_something();
}
class B extends A {
protected function do_something() {
// ...
}
}
It is not certainly a good idea to do so. It depends on what you want to achieve, and why. Creating derived classes in the parents constructor (like your previous example stated) is impossible. The language might allow it, but it will lead to an endless loop of instantiation. You will definitely need to explain why you are doing this. Otherwise nobody will be able to help you sufficiently.
This seems to be like a bad idea IMHO - it's going to require high maintenance and you are creating some tight couplings between classes.
i would recommend creating an abstract function in the parent that each of the children will implement with it's own logic.
[EDIT] since you are trying to iterate over all child objects i would recommend to create a base class that handles all the logic that needs to be implemented to all children, and override it in each of the child classes that need additional logic, and call the parent function inside it.
I think the big question should be why you would want it. I cannot come up with a solid design that would have a class extending something (the default example could be furniture, so for instance GardenChair extending Chair) be available in the parent class.
The whole idea is that it should be the other way around.
If you want to call the 'do_something', you should make an instance of the child, and let it call itself. If you need to enforce the do_something
, try it like this:
public abstract class A{
public abstract funcion do_something();
public function __constructor(){
$this->do_something();
}
}
public class B extends A{
public funcion do_something(){
...
}
}
public class C extends A{
public funcion do_something(){
...
}
}
精彩评论