警告:在cakephp中从空值创建默认对象

时间:2016-08-24 06:23:51

标签: php cakephp

我正在开发CakePHP 3.2

我有这个功能来查找产品类型(如果存在)

if ($product['product_type'] != null) {
   $getProductType = $this->ProductTypes->find()
     ->where(['title LIKE' => '%'.$product['product_type'].'%'])
     ->first();

   debug($product['product_type']);   // this is not empty
   debug($getProductType);            // this shows 'id' => 1 in array
   debug($getProductType->id);        // this shows 1

   if (!empty($getProductType)) {
      $p->product_type_id = $getProductType->id;           // line 11
      $p->subcategory_id = $getProductType->subcategory_id;
      $p->category_id = $getProductType->category_id;

      return $this->saveNewBulkProduct($product, $p->category_id, $p->subcategory_id, $p->product_type_id);
   }
}

但是这是警告

Creating default object from empty value on line 11
  

编辑print_r($getProductType)

的输出
App\Model\Entity\ProductType Object 
( 
   [id] => 3 
   [category_id] => 1
   ....
)

2 个答案:

答案 0 :(得分:2)

我认为没有必要声明$ p而不是在$ p中设置属性及其值,你可以传递$ getProductType对象的值,如下所述。

if ($product['product_type'] != null) {
   $getProductType = $this->ProductTypes->find()
     ->where(['title LIKE' => '%'.$product['product_type'].'%'])
     ->first();
   debug($product['product_type']);   // this is not empty
   debug($getProductType);            // this shows 'id' => 1 in array
   debug($getProductType->id);        // this shows 1
   if (!empty($getProductType)) {
      return $this->saveNewBulkProduct($product, $getProductType->category_id,  $getProductType->subcategory_id, $getProductType->id);
   }
}

答案 1 :(得分:1)

你必须在第11行声明第一个$p = new stdClass();