I have a data processor class which can only perform its primary function once all its member variables have been assigned a value:
class {
public $firstName;
public $lastName;
public $ssn;
public $accessKey;
public function __construct($data = null) {
if (is_array($data)) {
// Assign the value of any fields in $data to
// the corresponding member var
}
}
public processData() {
// *** CHECK IF ALL PROPERTIES HAVE VALUES ***
foreach ($this as $p=>$val) {
if ($val === null) {
return false;
}
}
doStuff();
}
}
Is there a more efficient or elegant way to verify that all properties have a value? It feels kind of PHugly to do it this way.
Well i would encapsulate the checks in a protected method like
_isValid()and then jsut doAnother thing to make tha actuall check more elegant would be to add a variable for
_requiredValuesand one for_valuesand have them both be arrays – instead of using individual member variables… this way you can check them wholesale using an array comparison function if you prefer.If you want easy access to individual values you could just add a getter like `public