我在从班级访问变量时遇到问题......
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;
}
}
}
我在全球课程中设置了这门课程'文件,稍后我将用户ID传递给以下脚本:
$u = new getuser($userid);
foreach($u->user as $user){
echo $user->username;
}
我希望这会给我用户的名字,但不是,我哪里错了?!
由于
答案 0 :(得分:2)
请在您的班级中将您的用户成员定义为公开
class getuser {
public $user = null;
//...
}
答案 1 :(得分:1)
要访问类属性,您必须将其声明为public或实现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;
}