PHP类构造函数将mysql行作为对象返回

时间:2012-07-31 06:49:35

标签: php mysql oop class constructor

有人可以提供一个如何实现这个目标的例子吗?我希望用这样的东西:

$user = new User($id = '5');
echo "hi {$user->firstName}\n";

对象应包含行中的所有字段,可能会有所更改。

提前致谢!

3 个答案:

答案 0 :(得分:1)

这里我创建逻辑原型

class user 
{
    protected $_table = 'tbl_user';
    protected $_db;       // stores the database handler
    public $_user;     // stores the user data

    protected function __construct($user_id)
    {
          $stmt = "SELECT * FROM $this->_table WHERE id='".(int)$user_id."'";
          if ($this->_db->query($stmt)){
              $fetch = $this->_db->mysql_query($stmt);
              $this->_user = mysql_fetch_row($fetch);
          }
    }    

}

 $obj_user=new user($user_id);
 // now you can access 
 $obj_user->_user->firstname

答案 1 :(得分:1)

例如(非常简化 - 显示其背后的想法)......

<?php
class User {
  /**
   * @var PDO
   **/
  protected $_dbh;

  protected $_userid;
  protected $_firstname;
  protected $_surname;

  /**
   * init database connection
   *
   * @return void
   **/
  private function _initDatabase() {
    try {
      $this->_dbh = new PDO('mysql:...');
    } catch(PDOException $e) {
      die('not able to connect: '. $e->getMessage());
    }
  }

  /**
   * load user data from database
   *
   * @return void
   **/
  private function _loadData() {
    $this->_initDatabase();

    // create sql statement and select data
    $SQL = "
      SELECT *
      FROM   users
      WHERE  userid = :userid
    ";

    $dbStatement = $this->_dbh->prepare($SQL);
    $dbStatement->bindParam(':userid', $this->_userid, PDO::PARAM_INT);
    $dbStatement->execute();

    // assign data
    $userdata = $dbStatement->fetch(PDO::FETCH_ASSOC);
    $this->_firstname = $userdata['firstname'];
    $this->_surname   = $userdata['surname'];
    // ... and so on
  }

  /**
   * construct
   *
   * @param  int $userid
   * @return void
   **/
  public function __construct($userid) {
    $this->_userid = intval($userid);

    $this->_loadData();
  }

  /**
   * overload __get
   *
   * @param string $key
   * @return mixed
   **/
  public function __get($key) {
    if(property_exists($this, '_'. $key)) {
      return $this->{'_'. $key};
    }
  }
}

$user = new User(5);
echo('Hi '. $user->firstname);
?>

答案 2 :(得分:-1)

你必须首先制作一个简单的php类来命名用户。 正确封装它。 写所有的getter和setter。

例如

class User
{
private $firstName = '';
public function getfirstName($firstName)
{
return $firstName;
}
public function setfirstName($firstName)
{
this.firstName = $firstName;
}
}

//How to use it.

$user = new User();
$user->serfirstName('Suryansh');
echo 'Hi '.$user->getfirstName();