Jump to content

Ways to use a class within a different class


Goldeneye

Recommended Posts

I do know how to do this but I am curious about whether or not there is a "preferred" way to do this. I know there are a couple ways to use a class (I'll call Alpha_Class) within another class (I'll class Beta_Class)

 

Let's say we have this simple class (Beta_Class):

class beta {
    function foo(){
    
    }
}

 

If I wanted to use the Alpha Class within the Beta Class, I could any number of things. For example:

class beta {
    function foo(){
        $this->alpha = new alpha;
        //$this->alpha->bar();
    }
}

 

Or you could simply use the $GLOBALS array to store instantiated objects in:

$GLOBALS['alpha'] = new alpha;
class beta {
    function foo(){
        //GLOBALS['alpha']->bar();
    }
}

 

You could even declare Alpha_Class as a static class and thus would not need to be instantiated:

static class alpha {
    static function bar(){}
}

class beta {
    function foo(){
        //alpha::bar();
    }
}

 

Those are the only ways I can think of right now. Are there any other ways to accomplish this? I was wondering which way is the best in terms of readability and maintainability.

The preferred ways are:

 

composition:

class Beta {
    public function __construct() {
        $this->alpha = new Alpha();
    }
}

 

aggregation:

class Beta {
    public function __construct(Alpha $alpha) {
        $this->alpha = $alpha;
    }
}

 

inheritance:

class Beta extends Alpha {}

 

As you notice $GLOBALS isn't part of them.

Aggregation is a new one to me. I only knew about composition and inheritance but I also knew using $GLOBALS is a poor programming practice as it can easily lead to overwritten data. I read up about using a Registry (a registry pattern) to store Objects in but that seems counter-productive and abusive to the Registry Pattern.

The Registry pattern is a global object and thus best avoided. Martin Fowler himself notes it should be a last resort instead of your first weapon of choice.

 

I read up about using a Registry (a registry pattern) to store Objects in but that seems counter-productive and abusive to the Registry Pattern.

 

How is that abusive? A Registry is used to store objects.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.