There are similar questions to this such as this but this is different - it's about validating constructor parameters using setters.
Here is my constructor:
public function __construct( $foo, $bar ) {
try {
$this->set_foo( $foo );
$this->set_bar( $bar );
} catch( Exception $e ) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
and here's one of the setters (pseudo-code):
public function set_foo( $foo ) {
if( $foo fails validation checks ) {
throw new InvalidArgumentException( '$foo is not valid' );
}
}
In my class there are more than 2 class variables and each has their own set of validation checks. So is my question (well, 2 really):
Why would I want to change my code to use PHP magic getters/setters (here) and have a cluttered __set( $name, $value )
function? There would have to be a set of conditionals in this function to determine the type of validation that is needed so why would want to do this in this situation?
What is an example use case of these magic methods? Surely they would only be a good choice if there a few class members or when there is no validation?
Many thanks.