[英]PHP5 variable scope and class construction
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: 我在全局“类”文件中设置此类,稍后我将用户ID传递给以下脚本:
$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 谢谢
please define your users member as public in your class like this 请像这样在您的班级中将您的用户成员定义为公开
class getuser {
public $user = null;
//...
}
in order to access a class property, you have to declare it public or implement getters and setters (second solution is preferable) 为了访问类属性,您必须将其声明为公共属性或实现getter和setter方法(最好使用第二种解决方案)
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.