Is it bad practice to have a database query in the constructor for a class in order to load it upon creating a new instance of it?
class Home
{
private $home_id = null;
private $home_name = null;
private $home_number = null;
private $home_street = null;
function __construct($home_id)
{
$do_query = $mysql_con->query("SELECT * FROM home WHERE home_id = '$home_id'");
while ($home_data = $do_query->fetch_assoc())
{
// Set all of the items in the object
$this->home_id = $home_data["home_id"];
$this->home_name = $home_data["home_name"];
$this->home_number = $home_data["home_number"];
$this->home_street = $home_data["home_street"];
}
}
}
I have been told before that this might be bad practice, to have a query that builds up the object in the constructor.
- If it is bad practice, why is it bad practice?
- What is the alternative?