【发布时间】:2014-11-19 15:45:10
【问题描述】:
我正在尝试在 PHP 中学习更好的 OOP,并且我已经尝试解决这个问题好几个小时了,需要一些帮助。我使用的是 php 5.4,所以我相信我可以使用后期静态绑定。
我有一个名为 DatabaseObject (database_object.php) 的类,它有一个名为 create 的函数,如下所示:
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;
}
}
我从我的 Cart 类(在一个名为 cart_id.php 的文件中)调用它,该类在一个名为 add_to_cart() 的函数中扩展 DatabaseObject,如下所示:
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;
}
静态的:create();正在调用该函数,但是当它到达时
$attributes = $this->sanitized_attributes();
它没有调用我的 DatabaseObject 类中的 sanitized_attributes 函数
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;
}
属性是
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;
}
我得到 echo "in create()" 以及 echo "table ".static:table_name,它确实显示了要保存到的正确表。我没有得到 echo $sql,也没有得到“In Sanitized”。如果我取出 static:create() 行,它会继续运行而不会出现问题,并在我的 return $amazon 语句中显示信息。 我的问题是,我应该如何从我的 add_to_cart() 函数中正确调用 create 函数? 如果您要否决我的问题,您能否解释一下为什么我不会再次重复相同的错误?谢谢!
【问题讨论】:
-
请以正确的缩进开始您的 OOP 冒险。
-
我发现很难在短时间内和没有太多上下文的情况下遵循您的代码,但是...您确定您正确使用了 static 关键字吗?除了声明静态成员和方法之外,它在php中是一个相对“新”的东西,更像是一个修复(它应该从基类到达类层次结构的顶部以检索最派生的方法或值)。 .. 为什么不只是“this->create()”?在您的基类中定义一个抽象的“get_table”方法并让派生类实现它,在创建时只需执行“this->get_table()”就完成了...