Forum Moderators: coopster
class B
{
function getData()
{
//--- Does some stuff.
}
}class A
{
var $ourObject;
function A($objectB)
{
$this->ourObject = $objectB;
}
// More codes follows...
function update()
{
//--- The following does not work.
//--- How do I gain access to the methods of
//--- the object being passed to class A?
$this->ourObject->getData();
}
}
Thanks in advance.
Do this:
class B
{
function getData()
{
//--- Does some stuff.
}
}
class A extends class B
{
NOTE: Once you extend the "superclass" (which is class B), there is no need to pass those methods of class B into class A, because class A is an extension of class B. Now, your object from class A can use all of class B's methods and properties when you use the NEW keyword. Make sure the NEW keyword is with class A and not class B
}
In your main code:
$widget=new A();
Now, your object $widget can use all the methods and properties of both class A AND class B.
I hope this helps.
Bruce
class B
{
function getData()
{
//--- Does some stuff.
return "Hello world";
}
}
class A
{
var $ourObject;
function A($objectB)
{
$this->ourObject = $objectB;
}
// More codes follows...
function update()
{
//--- The following does not work.
//--- How do I gain access to the methods of
//--- the object being passed to class A?
$data = $this->ourObject->getData();
print "$data\n";
}
}
$objB = new B();
$objA = new A($objB);
$objA->update();
brucec, I had your example originally, but as my object structure started to take shape, I realized that object b is not an extension of object a. From what I have read, isn’t inheritance only supposed to be used when the child class “is a” parent class. Such as a woman “is a” person. A man “is a” person. In my case, you could say I have a car class and a person class. Eventually, don’t you need to pass the person class to the car class so that person can interact with the car?
Maybe I have this wrong. As I said, I’m fairly new to working with OOP.
In any case, I would like to hear your response. I often wondered how you are supposed to encapsulate your objects so they can be “free standing” without them knowing anything about other objects. For example, eventually, the person class has to have some knowledge of the car class and how to use it. Once that happens, don’t you break the rules of encapsulation?
ExpLarry, I got your example to work.
Thank you all for the advice and code examples!
Same goes with passing a Car object into the Person class, this doesnt not break the rules of encapsulation, the Person class will only be able to access the the Public methods of the Car Object, but not the internal handling of the data, that is the private methods and private data manipulation.
regards,
Mark