如何在 PHP OOP 中正确调用函数


How to call a function correctly in PHP OOP

我正在尝试在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;
    }

static:create(); 正在调用函数,但当它到达

$attributes = $this->sanitized_attributes();

它没有调用我的数据库对象类中的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;
     }

我得到了回显"in create()"以及回显"表".static:table_name,它确实显示了要保存到的正确表。 我没有得到回声$sql,也没有得到"净化中"。 如果我取出 static:create() 行,它会继续没有问题,并向我显示我的返回语句中的信息$amazon。我的问题是,我应该如何从我的 add_to_cart() 函数正确调用创建函数?如果你要对我的问题投反对票,你能解释一下为什么,这样我就不会再重复同样的错误了吗? 谢谢!

由于您是静态调用 create 的,因此您必须静态调用同一类的任何其他方法,因为您不是在处理类的"实例",而是使用它的静态版本。

我不知道其余代码的结构,但您可以将static::create()更改为$this->create(),并将其中的静态调用创建为调用$this或将$this->sanitized_attributes()更改为static::sanitized_attributes()

另外,您应该避免使用全局变量。既然你要做OOP,你应该练习适当的依赖注入,并将这些全局变量传递给你的类,而不是使用global $blah