0

I have a user_id array:

$user_id = Array ();

And I want to create different variable names for each object:

//Something like $this->user_0, $this->user_1, $this->user_2, ...

$i=0;
foreach ($this->user_id as $id){
    $var = 'this->user'.$i;
    $$var = new DatabaseObject_User($db);
    $$var->loadForUser($db, $id);
    $i++;
}

I want Something like $this->user_0, $this->user_1, $this->user_2, different variables for each Object.

3
  • Why would you want to do this? Just use an array Commented Dec 11, 2013 at 2:00
  • @Travesty3 I want to create different variables: $this->user_0, $this->user_1, $this->user_2... for each Object Commented Dec 11, 2013 at 2:01
  • @82din: Got it. You might just want to comment on your code sample, so it's more obvious that it's an example of what you've tried that didn't work. Commented Dec 11, 2013 at 2:05

2 Answers 2

2

Don't do this. You will have no end of troubles attempting to iterate and test these properties.

Simply use an array, eg

class Whatever {
    private $user_id = []; // PHP 5.4 syntax, use array() if not applicable
    private $users = [];

    public function loadUsers() {
        foreach ($this->user_id as $id){
            $user = new DatabaseObject_User($db); // dunno where $db comes from
            $user->loadForUser($db, $id);
            $this->users[] = $user;
        }
    }

You can then access each user via an array index, eg

$this->users[n]; // where n is some integer; 0 <= n < count($this->users)

or iterate the array

foreach ($this->users as $user) {
    /* @var $user DatabaseObject_User */
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm making some tests with your solution, Can I access users like this: $this->users[n]->user_id ? thanks!
@82din: Assuming your DatabaseObject_User class has a public user_id property, yes.
0

Not sure why you would want them to be individual variables instead of just storing an array of users, but I think you're looking for this:

$i=0;
foreach ($this->user_id as $id){
    $var = 'user'.$i;
    $this->$var = new DatabaseObject_User($db);
    $this->$var->loadForUser($db, $id);
    $i++;
}

Keep in mind that it's generally a bad idea to dynamically declare class properties. It's not obvious that those properties exist and they're automatically made public. You might want to consider just using a $users class property.

1 Comment

Thank you @Travesty3, I did an update to the question

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.