Well, I have a configuration object that contains the settings for various kinds of objects. My classes are generated at runtime as soon as i want to intantiate a new object of a class that hasn’t been created so, they rely on the config object to know what attributes are mandatory and some other info:
think of it kinda like this:
Config
->Class1
->Attributes
->id
->Mandatory: true
->imagesource
->Mandatory: true
.................
->Class2
..........................
i have a method, validateObject() that checks if the mandatory values are all set for the object, like:
function validateObject($object){
$config = configObject[get_class($object)];
foreach($config->attributes as $attrName => $attrVal){
if($attrVal->mandatory == true){
if(!isset($object->$attrName){
throw Error();
}
}
}
}
So far, so good. It happens that now, my config object will have the attribute names turned into camelCase. I decided to let the programmer use any casing they wish so, in the end, i just want to check if the object has any property that, turned to lowercase, will match the one on the Config turned to lowercase to.
My current solution would be something like
function validateObject($object){
$config = configObject[get_class($object)];
foreach($config->attributes as $attrName => $attrVal){
if($attrVal->mandatory == true){
$lowercaseAttr = str_to_lower($attrName);
foreach($object as $key => $value){
if(str_to_lower($key) == $lowercaseAttr){
//don't throw, move to the next attribute in config
}
}
}
}
}
This would do the job, although it would need a bit more work. I was looking for a more elegant solution…
I hope i’m not being to confusing, thanks for your help
The only way I could think of doing this is to add a function to your class similar to
and then call
The array bit could probably be optimized, I just put this together quickly to see if it would work for you. If you had a number of classes then this function could sit separate and you could pass in an object
The above will return true if the property exists but is null. You can check the value by changing the function to