Forum Moderators: coopster

Message Too Old, No Replies

Object oriented method calling from a different class

can this be done?

         

ryan_b83

4:10 pm on Feb 4, 2007 (gmt 0)

10+ Year Member



Hello, how do you call a method from a class, while you are in a method of a differeent class?

EXAMPLE:

class ABC{
function APPLE{
//CODE GOES HERE
}
}

class XYZ{
function ORANGE{
$ABC->APPLE(); //I tried this, but i cant get it to work?
}
}

Anyone know? thanx

ryan_b83

4:28 pm on Feb 4, 2007 (gmt 0)

10+ Year Member



Actually, here is the EXACT code:


<?
class ABC{
function APPLE(){
echo "APPLE!";
}
}

class XYZ{
function ORANGE(){
$ABC->APPLE(); //I tried this, but i cant get it to work?
}
}

$ABC = new ABC();
$XYZ = new XYZ();

$XYZ->ORANGE();
?>

THE ERROR:

Fatal error: Call to a member function on a non-object in /home/mysite/public_html/test.php on line 11

ericjust

6:58 pm on Feb 4, 2007 (gmt 0)

10+ Year Member



Hi Ryan,

To make the code work how you have it written, you will have to add this line:

function ORANGE(){
global $ABC;
$ABC->APPLE();
}

The instance of class ABC (in this case $ABC) is not naturally accessible from within this class method. It's the same as any other variable declared outside a function or class. We need to bring in the global variable holding the instance of the class.

You can also call a static method from another class without having to use the instance of the class. If your method that you are calling (APPLE()) doesn't use $this-> than you can probably call the method from within another class like this:

function ORANGE(){
ABC::APPLE();
}

Hope this helps,
Let me know if you would like further explanation.