Accessing a child class from a fellow child class?
I have a parent class called sitewide and all my other classes are children of this. Sitewide has a bunch of stuff in it, and I'd like to organize it. I was thinking that, to do so, I'd group the things sitewide does together (e.g. database stuff, form checking stuff, etc.) and make an individual class for each category. So we'd have a database class, a form checking class, a layout class, etc. These would all be children of sitewide.
Now here's the thing. In my other child classes of sitewide (e.g. login, signup, forum, etc.) how would they access the layout stuff, form checking stuff, etc., now that they're in fellow child classes?
The better I get at programming, the more I appreciate arrays. Handy dandy things they are.
Actually, I think you're going to run into a lot of trouble with the architecture you just described. The classes you named most likely should not be descendants of sitewide. Instead, they should be independent components that sitewide makes use of.
Inheritance normally should pass the "is a" test. If your Database object is a type of Sitewide object, then it makes sense to use inheritance. Based on those names, however, I'm guessing that is not the case; in which case I suspect that your Database object probably should use the Sitewide object, perhaps passed to or instantiated by the Database class's constructor. (Passing it in makes that dependency more obvious, so I generally prefer that over having the class instantiate it itself -- but it's not a hard and fast rule.)
PHP Code:
class Database
{
private $sitewide;
public function __construct(Sitewide $sitewide)
{
$this->sitewide = $sitewide;
}
public function foo()
{
// you now have access to sitewide internally:
echo $this->sitewide->bar();
}
}
$sitewide = new Sitewide();
$db = new Database($sitewide);
$db->foo();
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Bookmarks