Dynamic Model attribute from string

Hi all, I have a Model form like this:




class LisForm extends Model

{

    public $id_lis;

    public $imp_I;

    public $imp_A;

    public $imp_U;

    public $imp_D;

    public $imp_V;




I need a function to set dynamically an attribute, depending from a variable type (I,A,U,D,V). For now i do something like this:




public function SetLis($type,$imp)

{

            switch ($type) {

                case "I":

                    $this->imp_I = $imp;

                    break;

                case "A":

                    $this->imp_A = $imp;

                    break;

                case "U":

                    $this->imp_U = $imp;

                    break;

                case "D":

                    $this->imp_D = $imp;

                    break;

                case "V":

                    $this->imp_V = $imp;

                    break;

            }

            ...


}



Is there a better way to do this in a single line of code?

I try using “eval” function like so: eval("$this->imp_".$type."=".$imp); but doesn’t works

can someone help me? Any suggestion?

Thank’s

What are you trying to do? Do you use the public attributes individually or are all of them just for this function?

Something like this:




$lis = new LisForm();

$lis->SetLis("A",10);



That doesn’t help me help you. I would need to understand what this is trying to do. As of now it’s hard for me to know what the vars do or how they are used. I’m trying to figure out if you even need them. Is this for a form?

[size=“2”]I can’t tell why you don’t just use one variable and set the value as it’s in a switch case that returns the same value in each case except it’s just assigned to a different variable name. It almost defeats the purpose of the switch case. If you post a little more [/size]information[size=“2”] i or someone else will be able to help you. [/size]




$lis =new LisForm(['imp_a',10]);

echo $lis->imp_a; //would output 10 and there is no need for all of the other vars but I don't know what your doing



Hi skworden thank’s for the help. Don’t think too at the example because my real situation is more complex.

I try to simplify what i need with this code.

As you can see, i use switch to know what field of the model i update, according to the $type variable.

The fact is that each field has a name like "imp_"+type

I’m searching a method to convert a string to the right name of the field.

thank’s for help.

I think what you might be looking for is something like this





$type = 'A';

$value = 10;


$lis = new LisForm();

$lis->{'imp_' . $type} = $value;



that way you don’t need your switch case

PHP Variable variables

Thank you very much skworden this is exactly what i mean.

In your example there’s a little error.

This is the right command:




$lis->{'imp_' . $type} = $value;



You’re welcome! I updated my comment.