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 に答える