Sharing object between 2 classes
Posted
by
Justin
on Programmers
See other posts from Programmers
or by Justin
Published on 2012-06-09T22:21:14Z
Indexed on
2012/06/09
22:46 UTC
Read the original article
Hit count: 187
php
|object-oriented
I am struggling to wrap my head around being able to share an object between two classes. I want to be able to create only one instance of the object, commonlib
in my main
class and then have the classes, foo1
and foo2
, to be able to mutually share the properties of the commonlib. commonlib
is a 3rd party class which has a property Queries
that will be added to in each child class of bar
. This is why it is vital that only one instance is created. I create two separate queries in foo1
and foo2
.
This is my setup:
abstract class bar{
//common methods
}
class foo1 extends bar{
//add query to commonlib
}
class foo2 extends bar{
//add query to commonlib
}
class main {
public $commonlib = new commonlib();
public function start(){
//goal is to share one instance of $this->commonlib between foo1 and foo2
//so that they can both add to the properites of $this->commonlib (global
//between the two)
//now execute all of the queries after foo1 and foo2 add their query
$this->commonlib->RunQueries();
}
}
© Programmers or respective owner