I am wondering what method is considered best practice, and why?
Having the function so it attempts to grab whatever is passed in.
class Test{
private $first = 'first';
private $second = 'second';
public function data($what){
return $this->{strtolower($what)};
}
}
or having a fixed set of options:
class Test{
private $first = 'first';
private $second = 'second';
public function data($what){
switch(strtolower($what)){
case 'first':
$value = $this->first;
break;
case 'second':
$value = $this->second;
break;
default:
$value = null;
}
return $value;
}
}
Using the first option means that I don’t need to alter the function every time I add a new member to the class, but it also means that I can no longer have private class members.
Using the second options means I need to alter the function every time I add a new member, but it means that I can make sure nothing is read that shouldn’t be.
With the first method if I want to add extra processing to particular members I can just add an if statement for those members.
With the second method I can do the processing inside the case statement.
Surely the code needs to know what to extrapolate from an object Dynamic is not better, being specific is not being sloppy with writing code. It means that you have used you brains to think about the consequences of that action.