I create a class called User
with only private member variables and getter/setter functions
class User {
private $m_id;
private $m_firstname;
private $m_lastname;
public function get_firstname() { return $this->m_firstnmae; }
public function set_firstname($firstname) { $this->m_firstname = $firstname; }
...
}
so print_r($user)
would give me something like this:
User Object
(
[m_id:User:private] => 2725
[m_firstname:User:private] => Alan
[m_lastname:User:private] => Turing
)
Now I am using PDO to insert the object into a database(I will skip the connection part, since it's working and not part of the problem). Here my function to insert the data:
function insert($user)
{
$insert_query = "insert into table (id,firstname,lastname) values (:id, :firstname, :lastname)";
try
{
$stmt = $this->m_pdo->prepare($insert_query);
$stmt->bindParam(':id', $user->get_id());
$stmt->bindParam(':firstname', $user->get_firstname());
$stmt->bindParam(':lastname', $user->get_lastname());
$stmt->execute();
return true;
}
catch (PDOException $ex)
{
echo $this->m_error_message = $ex->getMessage();
return false;
}
}
works as well. HOWEVER, when I change the php error_reporting to E_ALL | E_STRICT
, which show runtime strict warning as well, the insert code produce the warning strict standards only variables should be passed by reference
for the bindParam
lines. After asking google, I found out that obviously I have to do this in 2 steps:
$id = $user->get_id()
$stmt->bindParam(':id', $id);
After converting them into the new format, everything works without any warning.
The thing is, my original User-class
is much bigger with more then 20 private member variables and I have other classes like this as well. So I was thinking iterate through the variables and save them in an array and bindParam
them as array. But then I face the problem that foreach
only loop through the public variables but not the private ones... So my questions now:
bindParam
with a loop somehow?for convenience I use same naming-format everywhere. i.e. column in database with firstname
would have the counterpart m_firstname
in the User-class
with get_firstname()
and set_firstname($firstname)
as getter/setter
I think that you should use
public bool PDOStatement::bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )
Instead of bindParam() and keep your getters :)
moved from comment to answer