0

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

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

该对象应包含行中的所有字段,这些字段可能会发生变化。

提前致谢!

4

3 回答 3

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
于 2012-07-31T06:58:13.373 回答
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);
?>
于 2012-07-31T07:04:54.720 回答
-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();
于 2012-07-31T07:00:43.187 回答