1

Is it possible to have a construct like this. Say I have an array like this:

$names = array ('name1', 'name2', 'name3');
$values = array ('value1', 'value2', 'value3');

And then I want to do the following:

foreach ($names as $field) {
    $this->$field = $values[$counter];
    $counter ++;
}

So that later, I can access the said object like this:

$var1 = $object->name1;
$var2 = $object->name2;

// produces "value1"
echo $var1;

// produces "value2"
echo $var2;

What I want to do is to have an object, that has dynamically named fields. Is this possible with OO PHP?

Shade
  • 9,936
  • 5
  • 60
  • 85
  • 1
    Yes it is. Have you not tried it? Although the above code wont work, because you need to do `foreach ($names as $k => $name) $this->$name = $values[$k];` – DaveRandom Sep 02 '11 at 15:53
  • @DaveRandom: code works with `$counter`. Not the way I'd go but the result is the same. – webbiedave Sep 02 '11 at 15:56
  • 1
    I think this question was already answered here: http://stackoverflow.com/questions/829823/can-you-create-class-properties-dynamically-in-php – Sam Sep 02 '11 at 16:00
  • @webbiedave surely that won't work unless you create the `$counter` variable with a value of zero first? I'm absolutely positive it wont work on the first iteration... – DaveRandom Sep 02 '11 at 16:10
  • @DaveRandom: That's right. Since he's only showing code snippets I'm just assuming that it's initialized before the loop. – webbiedave Sep 02 '11 at 16:47

3 Answers3

4

Yep, that'll work, but generally Variable Variables are discouraged.

Perhaps the more elegant solution would be to use the __get magic method on the class like so:

class Person
{
    public function __construct($vars)
    {
        $this->vars = $vars;
    }

    public function __get($var)
    {
        if (isset($this->vars[$var])) {
            return $this->vars[$var];
        }

        return null;
    }
}

The vars array would then work as so:

$vars = array(
    'name1' => 'value1', 
    'name2' => 'value2', 
    'name3' => 'value3',
);

$object = new Person($vars);

Or if you specifically want to build it from the two arrays:

$vars = array_combine($names, $values)
paulmatthews86
  • 303
  • 1
  • 3
3

Yes, you can

$object = (object)array_combine($names , $values);

As suggested by @Sam, the Magic __set method works better

ajreal
  • 46,720
  • 11
  • 89
  • 119
1

Using a specially-configured ArrayObject, you can access members using either syntax:

$object = new ArrayObject(array_combine($names, $values), ArrayObject::ARRAY_AS_PROPS);

echo $object->name1;   // value1
echo $object['name1']; // value1