1

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

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

4

1 回答 1

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
于 2012-07-13T02:22:11.780 回答