openfrog
openfrog

Reputation: 40735

Which of these OOP options should I use?

I have two classes ClassA and ClassB. ClassA always needs an template file name, and ClassB extends ClassA.

In usual cases when a ClassB instance is created, the user has to specify the template file name. Like:

$classB = new ClassB('index');

But now I created a ClassX which extends ClassA, and when the user uses ClassX, he must not specify anything. It's a class that just creates a button, so it knows by itself what the template file for this is like.

So the user just wants to call:

$bttn = new ClassX();

and internally the constructor of ClassA is called with 'button_template'.

To do this, I see these choices:

A)

public function __construct() {
    $tplName = func_get_arg(0);
    if (!isset($tplName)) {
        $tplName = 'button_template';
    }
    parent::__construct($tplName);
}

Or B)

public function __construct($tplName='button_template') {
    if (!isset($tplName)) {
        $tplName = 'index';
    }
    parent::__construct($tplName);
}

Or C)

public function __construct($tplName='button_template') {
    parent::__construct($tplName);
}

Which one is the best? And why?

Upvotes: 1

Views: 130

Answers (3)

Addsy
Addsy

Reputation: 4054

C) gives the user the option of overriding the template, D) doesn't. I'd go with either of those depending on whether only the button template can used (d) or any template can be used but if none is specified the button template is used by default (c)

Upvotes: 0

Pim Jager
Pim Jager

Reputation: 32119

I think this is the best way:

#Class A:
public function __contruct($template){
  //do stuff
}

#Class X extends A
public function __contruct(){
   parent::__construct('button_template')
}

I feel this is the best way because Class A should not be concerned about What Class C wants (Case A) And Class C should not accept anything other then buton_template (Case B and C)

Upvotes: 1

openfrog
openfrog

Reputation: 40735

Since I don't want that the user specifies anything, maybe this one is the best:

(came in my mind after posting the question!)

D)

public function __construct() {
    parent::__construct('button_template');
}

Upvotes: 2

Related Questions