PHP - 使用类获取用户信息

时间:2012-07-12 20:21:33

标签: php class fetch

假设与数据库的连接以及对表和单元格的所有引用都是正确的......我怎么能得到这样的工作呢?

class User  
{  

    private $_display;  
    private $_email;  

    public function __construct($username)  
    {  

        $fetch_user = mysql_query("SELECT * FROM `registered_users` WHERE `user_name`='$username'");
        $fetch_user = mysql_fetch_array($fetch_user);

        $this->_display = $fetch_user['user_display'];  
        $this->_email = $fetch_user['user_email'];  
    }  

} 
$person1 = new User('username'); 
echo "Information: " . print_r($person1, TRUE);  

问题是它什么都不返回。调试时不会抛出错误或任何内容。虽然这是可行的方法吗? :S

1 个答案:

答案 0 :(得分:0)

这是粗略我会做什么:

<?php

  class User{

    private $username;
    private $data;

    public function __construct($username){
      $this->username = $username;
      if($this->valid_username()){
        $this->load();
      }
    }

    private function load(){
      // Let's pretend you have a global $db object.
      global $db;
      $this->data = $db->query('SELECT * FROM registered_users WHERE user_name=:username', array(':username'=>$this->username))->execute()->fetchAll();
    }

    public function save(){
      // Save $this->data here.
    }


    /**
     * PHP Magic Getter
     */
    public function __get($var){
      return $this->data[$var];
    }

    /**
     * PHP Magic Setter
     */
    public function __set($var, $val){
      $this->data[$var] = $val;
    }


    private function valid_username(){
      //check $this->username for validness.
    }  

    // This lets you use the object as a string.
    public function __toString(){
      return $this->data['user_name'];
    }

  }

使用方法:

<?php

  $user = new User('donutdan');
  echo $user->name; //will echo 'dan'
  $user->name = 'bob';
  $user->save(); // will save 'bob' to the database