Add properties to object using array keys

2019-07-25 01:17发布

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?

标签: php oop
3条回答
混吃等死
2楼-- · 2019-07-25 01:52

Yes, you can

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

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

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-25 01:56

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
查看更多
放荡不羁爱自由
4楼-- · 2019-07-25 02:03

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)
查看更多
登录 后发表回答