1

I have an object, that I would like to interact with dynamically. I would like to rename the game1_team1 in:

$default_value = $individual_match->field_match_game1_team1[0]['value'];

to be game1_team2, game2_team1, game2_team2, game3_team1, etc. Based on the loop they are in.

I have tried:

$dynamic = 'field_match_game'.$i.'_team'.$j;
$default_value = $individual_match->$dynamic[0]['value'];

but it returns

Fatal error: Cannot use string offset as an array

Update: Based on Saul's answer, I modified the code to:

$default_value = $individual_match->{'field_match_game'.$i.'_team'.$j}[0]['value'];

which got rid of the Fatal error, but doesn't return a value.

2
  • 1
    Why do people keep asking for variable variables? What the heck is wrong with arrays? Commented Oct 24, 2010 at 15:18
  • It is a 3rd party module that creates the object. Commented Oct 24, 2010 at 15:23

3 Answers 3

7
$individual_match->field_match_game1team1[0]['value'] = 'hello1';

$i = 1;
$j = 1;

$default_value = $individual_match->{'field_match_game'.$i.'team'.$j}[0]['value'];
Sign up to request clarification or add additional context in comments.

2 Comments

That doesn't cause the string offset error, but it doesn't return a value either.
That's because you dont have a value assigned in the first place. If you copied the full example then $default_value would contain 'hello1'. Do print_r on $individual_match and see for yourself.
0

'Renaming' is not possible unless you create a new property, and delete the old one. Access dynamic names like this:

$dynamic = "field_match_$i_team$j";
$default_value = $individual_match->$dynamic[0]['value'];

Note the $ between -> and dynamic.

Delete and create example:

$oldProperty = "field_match_1_team1";
$newProperty = "field_match_$i_team$j";
$hold = $individual_match->$oldProperty;
unset($individual_match->$oldProperty);
$individual_match->$newProperty = $hold;

1 Comment

Two challenges: 1. $dynamic = "field_match_$i_team$j"; doesn't seem to work because the variable is assumed to be $i_team... instead of $i. 2. The use of the $dynamic[0]['value'] returns "Fatal error: Cannot use string offset as an array"
0

Look at this : http://php.net/manual/en/function.get-class-vars.php You can list all object's properties in array and select only needed.

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.