1

I'm having problems with accessing variables from my classes...

class getuser {
    public function __construct($id) {
        $userquery = "SELECT * FROM users WHERE id = ".$id."";
        $userresult = mysql_query($userquery);
        $this->user = array();
        $idx = 0;
        while($user = mysql_fetch_object($userresult)){
           $this->user[$idx] = $user;
           ++$idx;
        }
    }
}

I'm setting this class in a global 'classes' file, and later on I pass through a user id into the following script:

$u = new getuser($userid);

    foreach($u->user as $user){
        echo $user->username;
    }

I'm hoping that this will give me the name of the user but it's not, where am I going wrong?!

Thanks

2
  • 1
    In terms of architecture I don't see exactly the scenario where you need to have a getUser class. Maybe you should consider a User class and maybe a Team class that has a getUsers () method. It depends on what you are doing with those users... Commented Feb 24, 2012 at 13:37
  • Adding error_reporting(E_ALL); to the top if these sorts of scripts can often help with debugging. Commented Feb 24, 2012 at 16:44

2 Answers 2

2

please define your users member as public in your class like this

class getuser {
    public $user = null;
    //...
}
Sign up to request clarification or add additional context in comments.

Comments

1

in order to access a class property, you have to declare it public or implement getters and setters (second solution is preferable)

class A {

  public $foo;

  //class methods
}

$a = new A();
$a->foo = 'whatever';

with getters and setters, one per property

class B {

  private $foo2;

  public function getFoo2() {
    return $this->foo2;
  }

  public function setFoo2($value) {
    $this->foo2 = $value;
  }

}

$b = new B();
$b->setFoo2('whatever');  
echo $b->getFoo2();

in your example:

class getuser {
    private $user;

    public function __construct($id) {
        $userquery = "SELECT * FROM users WHERE id = ".$id."";
        $userresult = mysql_query($userquery);
        $this->user = array();
        $idx = 0;
        while($user = mysql_fetch_object($userresult)){
           $this->user[$idx] = $user;
           ++$idx;
        }
    }

    /* returns the property value */
    public function getUser() {
      return $this->user;
    }

    /* sets the property value */
    public function setUser($value) {
      $this->user = $value;
    }

}


$u = new getuser($userid);
$users_list = $u->getUser();

    foreach($users_list as $user) {
        echo $user->username;
    }

1 Comment

Thanks for your answer, would you be able to use my code to explain what you mean?

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.