2

I have this class,

class example {
    public $a;
    public $b;
    public $c;
    ....
}

I have an array containing equal number of public variables as present in the example class (in this case 3):

$arr[0] = 'Red';
$arr[1] = 'Green';
$arr[2] = 'Blue';

I want to assign each value of this array to the public properties of the class one by one (Like $a gets Red, $b gets Green and so on). How do I assign these values from the array to the public properties of the class using a loop?

I was writing something like below, but it didn't work:

$class = new example();
$i = 0;
foreach ($class as $key => $value) {
    $class->$$key = $arr[$i];
    $i++;
}

EDIT:

Just to explain why I couldn't use any setter/getter method in example class - actually example class is created by unserializing a database object. I do not have any control on this class. I am working on a controller class which receives this example class and an array. I need to figure out a way to assign the values from this array to the public properties of example class.

6
  • A variable name cannot start with a number. You can't have $class->0 or $class->1 members. There are hackish ways to achieve it, but we'll settle on that you can't. However, your entire approach is wrong. Why doesn't your class have an array instead of a number of public members? Commented Oct 23, 2014 at 12:30
  • I agree with @N.B. - the approach is wrong. It's essentially hacking in some introspection. A better question would be why do you need to do it in a loop and is it really needed. To me it seems this is something the constructor can easily take care of, and even then, I'm not entirely sure it needs to be done in precisely this way. Commented Oct 23, 2014 at 12:34
  • 1
    @N.B. $key is not a number, it's the name of the public member properties of example class. Commented Oct 23, 2014 at 12:34
  • Guys - Thanks for telling my approach is wrong. Now please answer the question Commented Oct 23, 2014 at 12:35
  • 1
    Sorry, I misread the foreach and I thought you were iterating the array - apologies. Commented Oct 23, 2014 at 12:54

3 Answers 3

2

It doesn't work because of the double $$ when you assign the key:

$class->$$key = $arr[$i];

Change to a single $

$class->$key = $arr[$i];

Codepad demo

When accessing object properties without a variable, no $ is needed, therefore if your key is stored in a variable, a single $ is needed.

That said, there is likely a better way to solve the problem than this. Seems like the X Y Problem.

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

3 Comments

Your solution works for me, as is the solution from @raidenace below. Thanks for the X Y Problem link
In my comment to @N.B.'s answer, I have explained why I am unable to use 'a better way to solve the problem'
No problem - that's why I didn't offer any other suggestions because there were too many possibilities for what you were doing. Don't take the downvotes personally, any questions remotely related to "variable variables" don't go down well on SO because so many beginners use them when they aren't needed. In your case it sounds like you might be justified though.
2

Well, as I mentioned before - the approach is wrong. There are two answers that tell you how to do it, but it's not the best way.

This is a slightly better way, and it's smarter - because you have less code, less work and you can add as many properties as you want without ever touching the class.

The code:

class MyClass {

    protected $_data = array();

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

    public function __set($key, $value)
    {
        $this->_data[$key] = $value;
    }

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

Usage scenario #1:

$class = new MyClass;

$class->red = 'My red value';
$class->blue = 'My blue value';

Usage scenario #2:

$class = new MyClass;

$class->setData( array('red' => 'Red', 'blue' => 'Blue', 'green' => 'Green') );

The example serves to steer you towards magic functions __get() and __set() which you can use to your advantage and code the class (with proper data and value checking) in such a way that it's usable without having to declare its properties. This reduces complexity. Or you can use one of the given answers if they fit your scenario in a satisfactory way.

3 Comments

In my case, MyClass() is created through unserialize-ing a database-stored object. I have no control on this MyClass and can not add any magic method. I am working on a controller class which receives an array and MyClass and then I am supposed to assign the values from the array to the class. Hence I needed to figure out a way to iterate through the class properties and assign the values. Being new to PHP, it was kinda tricky for me! And SO is scary these days for all these downvotes :)
Well you see, it's much easier to grasp your problem when you include all the details. I understand that sometimes you are constrained with what you can or can't do and you have to resort to bad practice(s). I'll leave the answer in as an example, for when it's possible to have control over the object, how to dynamically add properties. It's also odd to save serialized object(s) to database, but I guess there's a reason behind that as well. Whatever the case, good luck with your task :)
Thanks. I am sure your answer will be valuable to others for whom this solution is applicable
1

Here you go:

<?php
class example {
    public $a;
    public $b;
    public $c;
}
$arr[0] = 'Red';
$arr[1] = 'Green';
$arr[2] = 'Blue';
$class = new example();
$i = 0;
foreach ($class as $key => $value) {
    $class->{$key} = $arr[$i];
    $i++;
}
var_dump($class);

The basic idea is to use $class->{$key} instead of $class->$$key, because $$key is a variable variable.

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.