2012-02-24 27 views
1
我在从我的类变量的访问问题

...PHP5变量的作用域和一流的施工

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; 
    } 

我希望这会给我的用户名,但它不是,我要去哪里错了?

感谢

+1

在建筑方面我没有看到正是你需要有一个类的getUser场景。也许你应该考虑一个User类和一个拥有getUsers()方法的Team类。这取决于你对这些用户做什么... – 2012-02-24 13:37:33

+0

添加error_reporting(E_ALL);如果这些脚本经常可以帮助进行调试,那么将它们置顶。 – Cerad 2012-02-24 16:44:47

回答

1

为了访问类属性,您必须声明它的公共或实现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; 
    } 
+0

感谢您的回答,您能否使用我的代码来解释您的意思? – Tim 2012-02-24 13:35:46

+0

好的等一下回答你,虽然很清楚 – 2012-02-24 13:37:15

2

请确定您的用户成员作为公众在你的类像这样

class getuser { 
    public $user = null; 
    //... 
}