Re: Calling child class from parent class [message #181094 is a reply to message #181092] |
Thu, 11 April 2013 21:15 |
Thomas 'PointedEars'
Messages: 701 Registered: October 2010
Karma:
|
Senior Member |
|
|
daveh(at)allheller(dot)net wrote:
> Is this possible?
>
> […]
> class GNP_DIRECTORY
> {
> public $m_rules;
> public $m_names; //array of GTCM_GNP object names
> public $m_cnt;
> […]
> public function register($name, $rule, $dat_file, $server, $port)
> {
> if(in_array($name, $this->m_names))
> {
> $this->m_rules[$name][] = $rule;
> return $this->m_names[$name];
> }
> $$name = new GTCM_GNP($this);
> if(!$$name)
> {
> return FALSE;
> }
> $this->m_cnt++;
> $this->m_names[] = $name;
> $this->m_rules[$name] = array($rule);
> return $$name;
> }
> }
>
> class GTCM_GNP extends GNP_DIRECTORY
> {
> […]
> public function do_something
> {
> return $this->variable;
> }
> }
> Basically I need to do: GNP_DIRECTORY[$$names]->do_something();
>
> or I want to do some method in GTCM_GNP by referring to a specific
> GNP_DIRECTORY
>
> Will this (pseudo)code work or is there a better approach.
Try to post a *reduced* *working* example next time.
So, first of all, why do you not try and see?
IIUC, in GNP_DIRECTORY::register() you want to append a new GTCM_GNP
instance to an array property of an GNP_DIRECTORY instance, and let it know
about the GNP_DIRECTORY instance it is related to:
public function register($name, $rule, $dat_file, $server, $port)
{
…
$item = new GTCM_GNP($this);
…
$this->m_items[$name] = $item;
…
}
Then you can of course call methods of the GTCM_GNP instance by using its
assigned name ($name) as index:
$dir = new GNP_DIRECTORY();
$dir->register($name, …);
$dir->m_items[$name]->do_something();
I would strongly suggest that the properties be “private” or “protected”,
though, and access to them be only possible through a getter, and if not
read-only, a setter.
I would also suggest renaming the classes if possible; only constants should
have identifiers that are all-uppercase. Use “GNP_Directory”, for example.
And, if possible, avoid cryptic class identifiers like “GTCM_GNP”; source
code should ideally be self-explanatory.
If you are looking for something else:
<http://www.catb.org/~esr/faqs/smart-questions.html#beprecise>.
And get a real name, please.
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f806at$ail$1$8300dec7(at)news(dot)demon(dot)co(dot)uk>
|
|
|