Reputation: 483
I have the following select statement which I am constructing a user object:
$stmt = $conn->prepare("SELECT user.User_ID, user.User_Name
FROM user");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_CLASS| PDO::FETCH_PROPS_LATE,'User');
I have the following class in a separate file, included with - require "User.php":
class User
{
private $User_ID;
private $User_Name;
public function __construct($User_ID, $User_Name)
{
$this->User_ID = $User_ID;
$this->User_Name =$User_Name;
}
I get the following warnings and notices -
Warning: Missing argument 1 for User::__construct()
Notice: Undefined variable: User_ID
It works fine but I turned on warnings etc as I am tidying up my code.
I have looked at other questions on here but the solutions don't seem to help and thought a fresh pair of eyes could help. A thought I had was I should have been passing an array in the setFetchMode() as the documentation states but that still seems to cause issues.
What is the correct way to create a class in PDO?
Upvotes: 2
Views: 763
Reputation: 32912
If you use arguments to User constructor, you need to use the third parameter in setFetchMode
public bool PDOStatement::setFetchMode ( int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
In your case
$stmt->setFetchMode(PDO::FETCH_CLASS| PDO::FETCH_PROPS_LATE,'User',
array('User_ID','User_name'));
or just provide default values for the constructor.
See the reference.
Upvotes: 1