1

I tried to do it by myself, but Google doesn't understand me. Question seems easy, unless I couldn't find answer.

I've got some object, and I want to change its value, so I can do it eg.

$obj->field_suffix1 = "Abracadabra";

The problem is that i want to pass "suffix1" from variable, so I would do if it was array

$obj['field_'.$suffix] = "Abracadabra";

Any suggestion? Thank you in advice! Dominik.

4 Answers 4

2

Try,

$obj->field_{$suffix} = "Abracadabra";
Sign up to request clarification or add additional context in comments.

1 Comment

You seem to have a bracket and then a curly brace
0

Use the $obj->$prop syntax:

o=new StdClass();
$p="someprop";
$o->$p="someval";
print_r($o);

//stdClass Object
//(
//    [someprop] => someval
//)

EDIT

Just to make that clear: I ment $p="field_$suffix"; $obj->$p = "Abracadabra";

1 Comment

Simpliest solution - the same as above ;) Great, thanks a lot.
0

This should be enough :

$yourfield = "field_".$suffix;
$obj->$yourfield = "Abracadabra";

1 Comment

That's it! Simple solution! I couldn't imagine it's SO simple! Thanks.
0

This works fine: https://eval.in/92882

$obj = array();
$suffix = "suffix1";
$key = 'field_'.$suffix;
$obj[$key] = "Abracadabra";

var_dump($obj);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.