...

View Full Version : Access One Child Class from Another



iLochie
04-28-2011, 08:03 AM
I have a main class, and multiple child classes that extend the main class. What I want to do is access a method of one child class in another child class. Here's an example:



class Hello {
public function __construct(){
echo("Hello. ");
}
}
class Message1 extends Hello {
public function __construct(){
$message = "I am 1.";
}
}
class Message2 extends Hello {
public function __construct(){
echo(parent::Message1); // This is what I am trying to figure out how to do. I need to access a variable declared by a sibling class.
}
}
$init = new Hello;
$message1 = new Message1;
$message = new Message2;


Any clarification on how to do this would be fantastic.

iLochie
04-28-2011, 08:28 AM
Found out I can initiate the first Message class, then pass that object to the next Message class, which will probably work for what I need it for. If anyone has a better solution I'd still like to hear it!

Fou-Lu
04-28-2011, 02:58 PM
No, that doesn't make any sense. Just as a parent is unaware of a child, a child is unaware of any siblings. The only way to do this is to either instantiate a new child or to pass an object to another object. The plus side is since they all inherit from the same class, any visible scope members or methods are available on any passed object as well, so you can access an inherited protected method from Hello in Message1 and Message2 from either of the class instances.

There is no reliable way to do this through the use of inheritance. While a parent can access a child through the use of dynamic binding on a method call, the runtime class is what determines which datatype is making the call, so you cannot tell which it was. get_class can tell you which runtime it is, but not about any other classes which could be done with some heavy reflection of all declared classes.
Depending on what you are doing depends if there is an easier way. A log interceptor for example would use a decorator, which allows you to wrap Logger into Logger over and over again, and when called it will determine which logger to call based on the provided information (ie: notice logger, warning logger, critical logger for examples).

iLochie
04-28-2011, 09:36 PM
Alright thanks, looks like I'll be passing the object then :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum