user1020317
user1020317

Reputation: 654

How do I push an element onto an array who's name is contained in a variable?

I'm making a generic php class which autoloads values into an object from a Database

To set properties I use this:

$object->$propertyName = $valueFromDB; where the value of propertyName is comes from the mysql field name..

Now I want to push something onto an array in a similar fashion:

This works..

$object->$arryName = array();

But this doesn't..

$object->$arryName[] = "test";

How can I work around this?

Upvotes: 0

Views: 65

Answers (1)

CaseySoftware
CaseySoftware

Reputation: 3125

$object->{$arryName}[] = "test"

The curly braces change the order of operations and will make PHP evaluate the variable name before the hard braces.

If you want to do a associative array, this gets a little more complicated:

$object->{$arryName}[$keyname] = "test"

In this case, you can put curly braces around $keyname but it's entirely optional.

On a related note.. variable variables are usually - but not always - a sign of something screwy. They're also a pain to whoever is coming after you who has to debug, refactor, do any grepping, etc. If you must use them, fine but make sure you've considered the ramifications.

Upvotes: 2

Related Questions