0

What should I put into class to be able to do so?

$data = array(
 'a' => 12345,
 'b' => 67890,
);

$object = new Class($data);

echo $object->a; //outputs 12345
echo $object->b; //outputs 67890

5 Answers 5

2

Ignacio Vazquez-Abrams’s answer is nice, but I'd prefer a whitelist of attributes you would like to allow to be set this way:

foreach(array('attribute1', 'attribute2') as $attribute_name) {
    if(array_key_exists($attribute_name, $data)) {
        $this->$attribute_name = $data[$attribute_name];
    }
}

This way you can make sure no private attributes are set.

Alternatively, if you're just after the object syntax, you can do:

$object = (object) $data;
$object = $data->a // = 12345

This is coercing the array into a StdClass.

Sign up to request clarification or add additional context in comments.

Comments

1
class A {
    private $data;

    public function __get($key) {
        return isset($this -> data[$key]) ? $this -> data[$key] : false;
    } 

    public function __construct(array $data) {
        $this -> data = $data;
    }
}

Comments

1
foreach($arr as $key => $val)
{
  this->$key = $val;
};

Comments

0
class MyClass {
    private $a;
    private $b;

    public function __construct(array $arr) {
        $this->a = $arr['a'];
        $this->b = $arr['b'];
    }
}

Comments

0

Depending on your UseCase, this might be an alternative to the given solutions as well:

class A extends ArrayObject {}

This way, all properties in the array will be accessible by object notation and array notation, e.g.

$a = new A( array('foo' => 'bar'), 2 ); // the 2 enables object notation
echo $a->foo;
echo $a['foo'];

As you can see by the class declaration, ArrayObject implements a number of interfaces that allow you to use the class like an Array:

Class [ <internal:SPL> <iterateable> class ArrayObject 
    implements IteratorAggregate, Traversable, ArrayAccess, Countable ]

It also adds a number of methods to complete array access capabilities. Like said in the beginning, this might not be desirable in your UseCase, e.g. when you don't want the class to behave like an array.

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.