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?

5
  • 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]; Commented Sep 2, 2011 at 15:53
  • @DaveRandom: code works with $counter. Not the way I'd go but the result is the same. Commented Sep 2, 2011 at 15:56
  • 1
    I think this question was already answered here: stackoverflow.com/questions/829823/… Commented Sep 2, 2011 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... Commented Sep 2, 2011 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. Commented Sep 2, 2011 at 16:47

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

3

Yes, you can

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

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

Comments

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

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.