Calling a Class from another Class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Calling a Class from another Class

Post 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);
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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.
User avatar
Sevengraff
Forum Contributor
Posts: 232
Joined: Thu Apr 25, 2002 9:34 pm
Location: California USA
Contact:

Post by Sevengraff »

you could try A::Times() or have class B extend class A.
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post 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 :D
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

The site phppatterns.com has lots of good OOP articles - maybe you know of it already.
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

Cheers Gruffy I will check it out now.
Post Reply