OOP beginner: classB extends classA. classA already object. method in classB needed.. etc
I'm learning myself to go from function based PHP coding to OOP. And this is the situation:
ClassA
holds many basic tool methods (functions). it's __construct
makes a DB connection.
ClassB
holds specific methods based on a certain activity (extract widgets). ClassB
extends ClassA
because it uses some of the basic tools in there e.g. a database 开发者_如何学Ccall.
In a php file I create a $a_class = new ClassA
object (thus a new DB connection).
Now I need a method in ClassB
. I do $b_class = new ClassB;
and call a method, which uses a method from it's parent::
ClassA
.
In this example, i'm having ClassA
'used' twice. Onces as object, and onces via a parent::
call, so ClassA
creates another DB connection (or not?).
So what is the best setup for this basic classes parent, child (extend) situation? I only want to make one connection of course?
I don't like to forward the object to ClassB like this $b_class = new ClassB($a_object); or is that the best way?
Thanks for thinking with me, and helping :d
It doesn't look like you need the instance of class A at all. Make sure that class B really is
a class A before using inheritance like this. Look into composition if you aren't sure.
From what I gather in your description, it sounds like class B should not really inherit from class A. Ask yourself - is B really an "enhanced version" of A? If not, and B is just using some utility from A, it should only call methods on it, or perhaps compose it (contain it as a member variable.)
As an aside, I don't think you should connect to the database in the constructor of A, unless you put some kind of protection around it to prevent duplicate connections. Probably better to have Connect() and Disconnect() functions so it's well understood when you are and are not connected.
$class_a = new ClassA();
$class_b = new ClassB($class_a);
class ClassB {
private $class_a;
public function __construct(ClassA $class_a) {
$this->class_a = $class_a;
}
}
If I did understand correctly what you wanted to do. This way you can ClassA methods in every method of ClassB without duplicating the connection to the database.
You could have another object that holds the Db connection that both class A and B can hook to. And its that class responsability to only make a single connection. You could look into the singleton patter for this
精彩评论