I know this may seem like a strange question, but say I have two classes;
class Class1 {
private $foo;
function addBar(Class2 &$bar)
{
$this->foo = $bar;
}
}
class Class2 {
private $foo
}
$a = new Class1;
$b = new Class2;
$a->addBar($b);
Is there any way Class2
can read information from Class1
? Even though they're in the same code block here, they are in seperate files in my script. The reason I need this is because I have Class2
linked by reference, but Class2
isn't allowed to be run until Class1
has been, and I know I could pass another variable to reference Class2
to Class1
(eg. $b->addFoo($a)
), but I would rather avoid that if possible.
I hope this can be done!
Thanks in advance
EDIT
Thanks to everyone who helped, I have decided to go another way around it. Thankyou again.
Class2
can call methods on Class1
objects, though it can't access private data. But it must have a reference to a Class1
instance in order to call any methods on it.
Your example doesn't show Class2
actually containing any code, and it sounds like you're trying to avoid calling methods on $b
. That doesn't make sense. Class2
can't "do" anything if you never call any methods on it.
class Class1 {
private $foo;
function addBar(Class2 $bar)
{
$this->foo = $bar;
$bar->addBar($this);
}
}
class Class2 {
private $foo
function addBar(Class1 $bar)
{
$this->foo = $bar;
}
}
$a = new Class1;
$b = new Class2;
$a->addBar($b);
class Class1 {
private $foo;
function addBar(Class2 &$bar)
{
$this->foo = $bar;
$bar->doSomething();
}
}
class Class2 {
private $foo
function doSomething()
{
//code
}
}
$a = new Class1;
$b = new Class2;
$a->addBar($b);
this way doSomething
in Class2()
is run after addBar()
in Class1