-1

Database connection

$db_user = 'root';
$db_pass='';
$db = new PDO('mysql:host=localhost;dbname=resource_management', $db_user, $db_pass);

Here the User class it's created

class User{     
    protected $username;
    protected $pass;
    public function __construct($username, $password){
        $this->username = $username;
        $this->password = $password;
    }   
    public function test(){     
        $sql = "select * from user";
        $data = $db->query($sql);
        while ($row = $data->fetch(PDO::FETCH_OBJ)){
            var_dump($row);
            echo $row->username;
        }
    }   
}

Here I try to test the User class

$user = new User('admin', 'test');
$user->test();
Deepu
  • 11,425
  • 13
  • 53
  • 87
micutzuclau
  • 27
  • 1
  • 5
  • 1
    such thing as PASSWORD must never be part of your code.. its only place is inside login/register functions. Once you have logged user you can fetch it usually with saved user id in a Session.. – Svetoslav Oct 21 '13 at 12:59
  • I hope next line isn't `if ($password == $row['password'])` (; – Francisco Presencia Oct 21 '13 at 13:10

1 Answers1

3

You'd normally pass it in the constructor or use a factory pattern that autoloads the arguments:

class Factory{
  public static function setdb($db) {
    self::$db = $db;
    }

  public static function getUser($role, $action) {
    return new User(self::$db, $role, $action);
    }

  public static function getUserPermissions($role, $action) {
    return new UserPermissions(self::$db, $role, $action);
    }
  }

Something like that. Note: I'm not a patterns expert and right now I'm learning about it, so the code above might contain bugs/not be perfect. Then you'd access it like:

$DB = new PDO(...);
factory::setdb($DB)

$User = Factory::getUser('admin', 'test');

I think the code is self-explanatory. Then you can add other methods to create more objects and automatically pass them the required variables so you don't need to be writing them all manually. It's called the Factory pattern. You can add more methods as you wish.

Note2: while globals is something that might come to mind, it's a terrible idea.

Community
  • 1
  • 1
Francisco Presencia
  • 8,240
  • 6
  • 40
  • 83