I saw how get_object_vars works at php.net.
The thing is that I can't make it work in my OOP script.
There's user.php file that extends DatabaseObject:
<?php
require_once('database.php');
class User extends DatabaseObject {
protected static $tableName = 'users';
protected static $tableID = 'id';
public $id;
public $username;
public $password;
public $firstname;
public $lastname;
}
?>
and here's databaseobject.php itself:
<?php
require_once('database.php');
class DatabaseObject {
public static function findAll(){
global $database;
$calledClass = get_called_class();
return self::findBySQL("SELECT * FROM ".static::$tableName."");
}
public static function findByID($id){
global $database;
$calledClass = get_called_class();
$result_array = self::findBySQL("SELECT * FROM ".static::$tableName." WHERE ".static::$tableID." = {$id}");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function findBySQL($sql){
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetchArray($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record){
$calledClass = get_called_class();
$object = new $calledClass;
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
$object_vars = $this->attributes();
return array_key_exists($attribute, $object_vars);
}
public function attributes(){
return get_object_vars($this);
}
protected function cleanAttributes(){
global $database;
$cleanAttributes = array();
foreach($this->attributes() as $key => $value) {
$cleanAttributes[$key] = $database->escapeValue($value);
}
return $cleanAttributes;
}
public function save() {
return(isset($this->id)) ? $this->update() : $this->create();
}
protected function create() {
global $database;
//$calledClass = get_called_class();
//$class = new $calledClass;
$attributes = $this->cleanAttributes();
$sql = "INSERT INTO ".static::$tableName." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_keys($attributes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true;
}else {
return false;
}
}
}
The create() function should take the values stored inside the public vars in users.php and store them in DB. now as the values of my vars I'm getting the attributes themselves as for $username I have value 'username'.
Where am I wrong? I'm newbie to OOP PHP... :P