views:

32

answers:

2

Hi. I am trying to get used to writing object oriented, but often I get a little stuck. I have this queries that I want to use to create arrays.

    $user1 = mysql_fetch_object(mysql_query("SELECT * FROM tbl WHERE username='$oc->user1'"));      
    $user2 = mysql_fetch_object(mysql_query("SELECT * FROM tbl WHERE username='$oc->user2'"));
    $user3 = mysql_fetch_object(mysql_query("SELECT * FROM tbl WHERE username='$oc->user3'"));

I can get the location of user1 by doing so: $location = $user1->location, but I want to create an array with all the locations to the users and I have tried this:

        for ($x = 0 ; $x < $users_total; $x++ ){

        $user = "user".($x + 1);            
        $user_location[$x] = $user->location ; //array med stedet alle brukerne befinner seg    

        } 

This should call $user1->location, $user2->location, $user3->location to array[0] [1] and [3]. But instead I get

Notice: Trying to get property of non-object

Whats the problem? Can't I add numbers to the string like this "user".($x + 1); and call the location $user->location. Isn't that the same as $user1->location?

+1  A: 

You need double dollar signs: try $$user->location. Otherwise, PHP thinks you're trying to do "user1"->location, which obviously isn't going to work.

Mark Trapp
+6  A: 

You want $$user->location. See variable variables. (Much) better yet, use arrays.

Artefacto
+1 for arrays, variable variables are seldom a good solution.
Wrikken