[英]PHP5 variable scope and class construction
我在從類中訪問變量時遇到問題...
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;
}
我希望這會給我用戶的名字,但不是,我哪里錯了?!
謝謝
請像這樣在您的班級中將您的用戶成員定義為公開
class getuser {
public $user = null;
//...
}
為了訪問類屬性,您必須將其聲明為公共屬性或實現getter和setter方法(最好使用第二種解決方案)
class A {
public $foo;
//class methods
}
$a = new A();
$a->foo = 'whatever';
有吸氣劑和二傳手,每個屬性一個
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.