Page 1 of 1
Calling a Class from another Class
Posted: Sun Oct 19, 2003 1:49 pm
by Gen-ik
Just wondering how I would call a function in class A from class B.
An example follows.....
Code: Select all
class A
{
function Times($arg)
{
echo $arg * 2;
}
}
$a = new A();
class B
{
function Double($arg)
{
global $a;
$a->Times($arg); // Trying to use the Times function in class A
}
}
$b = new B();
$b->Double(5);
Posted: Sun Oct 19, 2003 2:35 pm
by volka
if you try that you will see it works that way.
But relying on another global object should be avoided. The way you use that method it doesn't harm to derive B from A. I'm always suspicious if something outside the class not beeing part of the api is called.
Posted: Sun Oct 19, 2003 4:45 pm
by Sevengraff
you could try A::Times() or have class B extend class A.
Posted: Sun Oct 19, 2003 5:11 pm
by Gen-ik
Yeah your right the example does actually work (doh!).
The reason I'm working this way is because I'm creating a 'module' based collection of php classes. For example one class might deal with MySQL functions and another class might deal with sessions.
Any of the 'modules' can then be included in the web sites I create and they all need to be able to talk to each other.
I have a master class which checks which classes have been included in the web site and then acts as the parent to classes.
Might sound a bit weird but it seems to be working ok at the moment

Posted: Sun Oct 19, 2003 5:20 pm
by McGruff
The site phppatterns.com has lots of good OOP articles - maybe you know of it already.
Posted: Sun Oct 19, 2003 5:27 pm
by Gen-ik
Cheers Gruffy I will check it out now.