Matt Brunmeier
Matt Brunmeier

Reputation: 1310

Basic PHP inheritance

I'm brand new to OOP and I have a question that's gotta be pretty damn basic, but I'm having trouble explaining it in a concise way so it's hard to search for answers.

I have an application that supports credit card processing and I want to abstract the processing capabilities so I can add other providers (linkpoint, authorize.net, etc). I think what I want to do is create a simple class that looks something like this:

class credit {

    function __construct($provider){
        // load the credit payment class of $provider
    }

}

Then I'll have the providers each extend this class, eg

class linkpoint extends credit { }

But I really want to use the credit class more like an interface, sort of. I don't want a credit object, I want to do something like:

$credit = new credit('linkpoint');

Then I want $credit to be an instance of the linkpoint class. Or at least, I want all the methods to execute the code defined in the linkpoint class.

What's the best way to approach that? Or is there a better way to do it?

Upvotes: 3

Views: 125

Answers (4)

Johannes Klauß
Johannes Klauß

Reputation: 11020

I'm not sure if I'm getting this right, but when you want to $credit being an instance of linkpoint then you just have to do

$linkPointCredit = new linkpoint();

Btw. Your class names should always start with a capital letter.

Update:

Then you can indeed use a factory pattern.

class Credit
{
    private $provider;

    public function __construct($provider)
    {
        if(class_exists($provider) {
            $this->provider = new $provider();
        }
    }
}

Upvotes: 4

Xeoncross
Xeoncross

Reputation: 57184

I would recomend "Dependancy Injection".

class credit {

    function __construct(Provider $provider)
    {
        $this->setProvider($provider);
    }

}

class Provider {}
class Linkpoint extends Provider {}
class crossave extends Provider {}
class Debitcentral extends Provider {}

Then you can use them like:

$linkpoint = new Linkpoint();
$credit = new Credit($linkpoint);

$crossave = new Crossave();
$credit = new Credit($crossave);

$debitcentral = new Debitcentral();
$credit = new Credit($debitcentral);
// etc...

Upvotes: 0

Brian
Brian

Reputation: 15706

What you have described sounds like a Factory Design Pattern. Except instead of using the constructor, you would have a class (static) method on your base Credit class which returns an instance of one of your subclasses, depending on the string that was passed.

Upvotes: 1

dan-lee
dan-lee

Reputation: 14492

This is called "factory pattern" (see also Design patterns)

You can handle it like this

class Credit
{
  public function __construct($factory)
  {
    $object = null;

    switch($factory) {
      case 'linkpoint':
        $object = new linkpoint();
        break;
      case 'xy':
        //...
    }
    return $object;
  }
}

Upvotes: 5

Related Questions