maha_funk
maha_funk

Reputation: 497

Creating an array of Objects and then setting the member variables

This is the class that I have created in PHP

class userinfo
    {
        public $username;
        public $totalscore;
        public $userid;
    }

The code below is in a finite loop, and i is set to 0 before entering the loop. And the variable user_array is defined to be an array using the following code:

$user_array = array();

(some code here...)

    $i++;
    $user_array[i] = new userinfo();
    $user_array[i]->totalscore = $stattotal;
    $user_array[i]->userid = $id;

For some reason I cant understand why this wont work. I need to create an array of objects. And each object must hold three variables. How do I go about doing so ?

Thank you in Adv. for your Help !

Upvotes: 0

Views: 52

Answers (3)

Farid Movsumov
Farid Movsumov

Reputation: 12725

You can use get_class_vars method to get all properties of class

$my_class = new myclass();

$class_vars = get_class_vars(get_class($my_class));

foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}

SOURCE : http://php.net/manual/en/function.get-class-vars.php

Upvotes: 0

Dom
Dom

Reputation: 7315

Worked fine for me, remember the $ when using variables.

http://phpfiddle.org/main/code/muv-yx6

Upvotes: 1

silkfire
silkfire

Reputation: 25945

You must have a dollar sign ($i) before all variables in PHP.

Upvotes: 1

Related Questions