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.
This article may give you some architecture ideas: From flat PHP to Symfony2.
There are reasons to use parent child.
I prefer to think of and just use the parent as the basic template with the child as the exact type of class needed.
If one child OBJECT needs data from another use getter methods.
Same goes for GETTERS.
protect the properties
public the setter getter methods.
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.)
public function __construct(Sitewide $sitewide)
$this->sitewide = $sitewide;
public function foo()
// you now have access to sitewide internally:
$sitewide = new Sitewide();
$db = new Database($sitewide);
"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
How to Ask Questions the Smart Way
(not affiliated with this site, but well worth reading)
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)