Handle order dependence in loops
Posted
by Matt
on Stack Overflow
See other posts from Stack Overflow
or by Matt
Published on 2010-05-15T09:28:33Z
Indexed on
2010/05/15
10:04 UTC
Read the original article
Hit count: 320
Hey all,
I'm making a templating system where I instantiate each tag using a foreach loop. The issue is that some of the tags rely on each other so, I'm wondering how to get around that ordering from the looping.
Here's an example:
Class A {
public $width;
__construct() {
$this->width = $B->width; // Undefined! Or atleast not set yet..
}
}
Class B {
public $width;
__construct() {
$this->width = "500px";
}
__tostring() {
return "Hello World!";
}
}
Template.php
$tags = array("A", "B");
foreach ($tags as $tag) {
$TagObj[$tag] = new $tag();
}
echo $TagObj['A']->width; // Nadamundo!
EDIT: Ok just to clarify.. My main problem is that Class A relies on Class B, but class A is instantiated before class B, so therefore width has not yet been defined in class B. I am looking for a good way to make sure all the classes are loaded for everyone allowing the interdependencies to exist. For the future, please don't consider any syntax errors.. I just made up this example on the spot. Also assume that I have access to class B from class A after class B gets instantiated.
I know this has applications elsewhere and I'm sure this has been solved before, if someone could enlighten me or point me in the right direction that'd be great!
Thanks! Matt Mueler
© Stack Overflow or respective owner