Question

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?

Was it helpful?

Solution

$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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top