我在访问类中的变量时遇到问题。。。
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;
}
}
}
我在一个全局"classes"文件中设置这个类,稍后我将用户id传递到以下脚本中:
$u = new getuser($userid);
foreach($u->user as $user){
echo $user->username;
}
我希望这能给我用户的名字,但事实并非如此,我哪里错了?!
感谢
请将您的用户成员定义为类中的公共成员,如下
class getuser {
public $user = null;
//...
}
为了访问类属性,您必须将其声明为公共或实现getter和setter(第二种解决方案更可取)
class A {
public $foo;
//class methods
}
$a = new A();
$a->foo = 'whatever';
带有getter和setter,每个属性一个
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();
在您的示例中:
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;
}