Sharing classes

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
User avatar
rbx
Forum Newbie
Posts: 5
Joined: Mon Nov 03, 2008 4:14 pm

Sharing classes

Post by rbx »

I would like to know your opinion about the following problem:

There are 2 classes, say we class A and class B. I need to use object of class A inside the class B. Most important for me is usability and flexibility of the code. For example I don't think that implementation like create objects A and B in the main program and then use object A inside class B as global variable is good practice. So two ways come to my mind - 1) pass the object A into the constructor of class B or 2) include class A definition in the file where class B is defined and create instance in the constructor of class B. What is the best implementing practice? Is there any other better solution?

Thanks
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Re: Sharing classes

Post by infolock »

That's what extends is for ;)
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Sharing classes

Post by Christopher »

Of the three options:

Code: Select all

class A {
}
// inherit class
class B extends A {
    public function __construct() {
    }
}
// hard code class internally
class B {
    public function __construct() {
        $this->a = new A;
    }
}
// composite object
class B {
    public function __construct($a) {
        $this->a = $a;
    }
}
I would recommend doing the last one whenever possible because it allow polymorphism. Use the first two when hard coding the relationship is necessary or beneficial.
(#10850)
User avatar
rbx
Forum Newbie
Posts: 5
Joined: Mon Nov 03, 2008 4:14 pm

Re: Sharing classes

Post by rbx »

I cannot use option one because there is no such relationship between the two classes. Actually I am usually using opt 3, just wanted to know if there is some better way. Thanks
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Re: Sharing classes

Post by infolock »

arborint wrote:Of the three options:

Code: Select all

class A {
}
// inherit class
class B extends A {
    public function __construct() {
    }
}
// hard code class internally
class B {
    public function __construct() {
        $this->a = new A;
    }
}
// composite object
class B {
    public function __construct($a) {
        $this->a = $a;
    }
}
I would recommend doing the last one whenever possible because it allow polymorphism. Use the first two when hard coding the relationship is necessary or beneficial.

Good point :oops:
Post Reply