Hi everyone, I have some php code that I would like to share with you. I’m trying to visualize what is actually taking place with the instantiate method below. All the code works and I have more code but its just another class that has methods that perform like the mysql_fetch_array and the mysql_query. I get what the code does but I’m to visualize how it works if that makes any sense.
Thanks for any help, highly appreciated!
index.php: Here is just a few lines that I test it with.
$user = User::find_by_id(1);
echo $user->username;
user.php
<?php
class User {
public $id;
public $username;
public $first_name;
public $last_name;
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
public static function find_by_id($id=0) {
$result_array = self::find_by_sql("SELECT * FROM users WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
private static function instantiate($record) {
$object = new self;
foreach($record as $attribute => $value) {
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}
}
?>