Better way to handle value conversion for mixed variable types in an array, PHP -


i'm working [generally not used] php framework in class i'm working has array of fields correlate columns in sql.

well, setting values class objects there's class method setfieldvalue , conventionally done:

protected $fields = array('id', 'name', 'body');  function setfieldvalue($field, $value) {     switch($field) {         case 'id':             return parent::setfieldvalue($field, intval($value));         case 'name':             return parent::setfieldvalue($field, strval($value));         case 'body':             return parent::setfieldvalue($field, strval($value));     } } 

i'm looking bit more dynamic (and cleaner, i'll have many fields), maybe like:

protected $fields = array('id' => 'intval', 'name' => 'strval', 'body' => 'strval');  function setfieldvalue($field, $value) {     if(array_key_exists($field, $this->fields)) {         return parent::setfieldvalue($field, $fields[$field]($value));     } } 

would consider alternative i'm suggesting bad practice , furthermore suggest other alternatives?

no, looks because name of fields aren't promoted outside of class in both cases - switch or array_key_exists. should not make difference, because solve internally (privately) invisible.

run unit-tests before , after changes see if went smoothly.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -