In PHP possiamo inizializzare una classe con i dati presi da un database.
La soluzione รจ la seguente:
class Employee {
protected $data;
protected $id;
public function __construct($id) {
$this->id = $id;
$this->data = $this->loadData();
}
protected function loadData() {
if(is_int($this->id)) {
require_once('Database.php');
$db = new Database();
$query = "SELECT * FROM employees WHERE id = {$this->id}";
$result = $db->getResults($query);
return json_decode(json_encode($result[0]));
} else {
throw new Exception('Invalid ID.');
}
}
public function getId() {
return $this->id;
}
public function getData() {
return $this->data;
}
public function __toString() {
$data = $this->data->first_name . ' ' . $this->data->last_name . ' was born on ' . $this->data->birth_date . '. Hired on ' . $this->data->hire_date . '.';
return $data;
}
}
Esempio d'uso:
require_once('Employee.php');
$employee = new Employee(100);
echo $employee;