It seems that often I will want to execute some methods from a Class when I call it and choosing which function will depend on some condition. This leads me to write classes like in Case 1 because it allows me to rapidly include their functionality. The alternative would be Case 2 which can take a lot of time if there is a lot of code and also means more code being written twice when I drop the Class into different pages.
Having said that, Case 1 feels very wrong for some reason that I can't quite put my finger on. I haven't really seen any classes written like this, I suppose.
Is there anything wrong with writing classes like in Case 1 or is Case 2 superior? Or is there a better way? What the advantages and disadvantages of each?
Case 1
class Foo {
public function __construct($bar) {
if($bar = 'action1') $this->method1();
else if($bar = 'action2') $this->method2();
else $this->method1();
}
public function method1() { }
public function method2() { }
}
$bar = 'action1'
$foo = new Foo($bar);
Case 2
class Foo {
public function __construct() { }
public function method1() { }
public function method2() { }
}
$foo = new Foo;
$bar = 'action1';
if($bar == 'action1') $foo->method1();
else if($bar == 开发者_开发百科'action2') $foo->method2();
else $foo->method1();
If object initialization requires one of the methods to be called, then call one. Otherwise the second form is acceptable.
精彩评论