PHP Casting Variable as Object type in foreach Loop

前端 未结 5 562

Within the following code, $quiz_object->personalities contains an array of Personality objects.

// Loop through each personality th         


        
5条回答
  •  清歌不尽
    2021-02-01 15:48

    You can always call out to a separate function from within the foreach, and declare the class in the function declaration. This might also have the benefit of letting you reuse this code elsewhere. For example inside the function getPriceFromProduct below, you see how I declare the class of $product to be Product.

    Of course I agree it would be nice to not have to do it this way but hey, it works.

    class ProductBundle {
    
      private $products; //buy this
      public function get_products() { return $this->products; }
      public function add_product($product) { $this->products[] = $product; }
    
      public function get_price() {
            $products = $this->get_products();
            $prices = array();
            foreach($products as $product) {
                $prices[] = $this->getPriceFromProduct($product);
            }
            return array_sum($prices);
        }
    
        private function getPriceFromProduct(Product $product) {
            $price = $product->get_price();
            return $price;
        }
    

提交回复
热议问题