I am attempting to learn better OOP in PHP and I have been trying to resolve this for a number of hours now and need some assistance. I am using php 5.4 so I believe I can use late static binding.
I have a class called DatabaseObject (database_object.php) which has a function called create that looks like:
public function create() {
echo "in Create() ";
global $database; echo "<br> table: ".static::$table_name;
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO " .static::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')"; echo $sql;
if($database->query($sql)) {
$this->id = $database->insert_id();
return TRUE;
} else {
return FALSE;
}
}
I am calling this from my Cart class (in a file called cart_id.php)that extends DatabaseObject in a function called add_to_cart() which looks like:
public function add_to_cart($cart_id,$isbn) {
global $database;
$isbn = $database->escape_value($isbn);
$amazon = Amazon::get_info($isbn);
//get cart id if there is not one
if (empty($cart_id)) {echo " getting cart_id";
$cart_id = static::get_new_cart_id();
}
if(!empty($amazon['payPrice']) && !empty($isbn)) {
echo "<br> getting ready to save info";
$cart = new Cart();
$cart->price = $amazon['payPrice'];
$cart->qty = $amazon['qty'];
$cart->cart_id =$cart_id;
$cart->isbn = $isbn;
if(isset($cart->cart_id)) {
echo " Saving...maybe";
static::create();
}
}
return $amazon;
}
The static:create(); is calling the function, but when it gets to
$attributes = $this->sanitized_attributes();
it is not calling the sanitized_attributes function which is in my DatabaseObject class
protected function sanitized_attributes() {
echo "<br>in Sanatized... ";
global $database;
$clean_attributes = array();
//Sanitize values before submitting
foreach($this->attributes() as $key=>$value) {
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
Attributes is
protected function attributes() {
//return get_object_vars($this);
$attributes = array();
foreach (static::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
I get the echo "in create()" as well as the echo "table ".static:table_name, which does show the correct table to save to. I do not get the echo $sql, nor am I getting the "In Sanitized". If I take out the static:create() line, it continues on without a problem and shows me the information in my return $amazon statement. My question is, how am I supposed to correctly call the create function from my add_to_cart() function? If you are going to down vote my question, could you please explain why so I do not duplicate the same error again? Thanks!