Add properties to object using array keys

2019-07-25 01:24发布

问题:

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?

回答1:

Yes, you can

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

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



回答2:

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)


回答3:

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


标签: php oop