class MyClass {
function __construct($inputArg) {
if($inputArg == 1) {
// do this
}
else {
// do that
}
}
}
// later
$x = new MyClass (1);
Ok, I’ve realized that the above works. The value 1 arrives safely at the constructor, but is this good coding practice? The idea is to have a single class with some custom behavior depending on the calling argument. Better to have separate classes?
I wouldn’t recommend exposing the logic outside the class. Using an if/else statement to change the implementation seems fine though context could make something else a more viable solution.
class foo {
public function __construct($do) {
switch($do) {
case 1:
$this->_doOne();
break;
default:
$this->_doDefault();
}
}
private function _doDefault() { }
private function _doOne() { }
}
Branching in a constructor is done quite often by just about everyone one who works with PHP. Ultimately I think it comes down to personal preference. I wouldn’t over think it too much.
If the argument amounts to whether you construct a “dog” or a “cat”, you should abandon this approach and extend the base class with “dog” and “cat” classes that have their own constructors.
If the argument decides whether a simple “animal” class has fur or not, there’s nothing wrong with this approach.
Well basically it depends on personal preferences. But if you want to make it easier and more standard you should have at least some more methods to handle the situation but still you can have a condition directly in the constructor itself.
Edit:
class MyClass {
public function __construct() {
}
public function methodOne(){
}
public function methodTwo(){
}
}
// later
$val = 1;
//$x = new MyClass($val);
$x = new MyClass();
if($val == 1){
$x->methodOne();
}
else{
$x->methodTwo();
}