Question

i have ini files that are parsed and set to a class which sets each value to either a constant or a class variable. such as this;

function set_val($vals){
    define('VAL,$val['val']);
    define('val1,$val['val1']);
    ....

this setting of constants/vars continues for up to 20 values.

what is the appropriate way to ensure that the $val['val1'] value is set in terms of OOP? it would seem as if writing many isset()s is inappropriate.

would it be appropriate to create a generic class that takes the $vals array and ensures the key value exists?

if i use a generic class as mentioned above its my understanding that rules of oop (composition over inheritance?) say i shouldn't create the generic class object inside of the set vals method?

what is an appropriate solution to ensure the keys exist while loading a config as far as OOP is concerned?

ps (i know im not supposed to use constants but at this point without changing lots of code i'm not sure how to do this)

No correct solution

OTHER TIPS

I know this will involve a lot of isset() but yea, this is the best solution I could come up with

function set_val($vals){
    isset($val['val']) ? define('VAL,$val['val']); : 'false'; //Ignore false
<?php

$ini_values=array('CONSTA'=>1,'CONSTC'=>3); //For testing

set_val($ini_values);

function set_val($ini_values){
$required_consts=array('CONSTA','CONSTB','CONSTC'); //Array of constants you need
//...
 foreach($required_consts as $required_const){
  if(!empty($ini_values[$required_const])){
   define($required_const,$ini_values[$required_const]);
  }else{
    echo"<br />Value for $required_const missing<br />"; //Handle here
  }
 }
//...
}

//Show result for testing
echo CONSTA;
echo'<br />';
echo CONSTB;
echo'<br />';
echo CONSTC;

?>

Output:

Value for CONSTB missing
1
CONSTB
3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top