FairyBusiness
asked on
Am I dealing with late static bindings correctly in php??
Hi,
I have a class DatabaseObjects that is a child of a class Users. I decided to take some of my common functions from Users and put them into a class that can be used for other things as well.
I thought I should replace:
self::$table with static::$table
Is that not the way to do it? http://auroriella.com/index.php
I have a class DatabaseObjects that is a child of a class Users. I decided to take some of my common functions from Users and put them into a class that can be used for other things as well.
I thought I should replace:
self::$table with static::$table
Is that not the way to do it? http://auroriella.com/index.php
<?php
require_once 'includes/database.php';
class DatabaseObject {
// Common Databaes Methods
protected static $table = "users";
private $object;
public static function find_all() {
return static::find_by_sql("SELECT * FROM " . static::$table);
}
public static function find_by_id($id=0) {
global $database;
$result = static::find_by_sql("SELECT * FROM " . static::$table . " WHERE id={$id} LIMIT 1");
return !empty($result) ? array_shift($result) : false; //array_shift pulls the first item out
}
public static function find_by_sql($sql="") {
global $database;
$result = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result)) {
$object_array[] = static::instantiate($row);
}
return $object_array; // Must return an array!
}
private static function instantiate($record) {
$class_name = get_called_class();
$object = new $class_name; // Here is where it starts a new class for itself
foreach($record as $attribute => $value) {
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
// get_object_vars returns an associative array with all attributes
// (including private ones) as the keys and their current value as the value
$object_vars = get_object_vars($this);
// We don't care about the value, we just want to know if the key exists
// Will return true or false
return array_key_exists($attribute, $object_vars);
}
} // End class User
?>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Open in new window