title: How can I SUM this class property in PHP so I get the total value for all class instances?
body: <p>I'm using the PHP MVC framwork, Yii. I have a model called <strong>Category</strong> that has a <code>HAS_MANY</code> relationship to <strong>Product</strong> model. Both model classes extend <a href="http://www.yiiframework.com/doc/api/CActiveRecord" rel="nofollow">CActiveRecord</a>.</p>
  
  <p>I'm looking for help in understanding some specific ways that OOP is working in PHP.</p>
  
  <p>In my a View for my Category Model, I'm trying to find the total inventory count for the Category. For instance, I could do this:</p>
  
  <pre><code>&lt;?php
  $total_inventory = 0;
  foreach($category-&gt;products as $product)
    $total_inventory = $total_inventory + $product-&gt;inventory;
  echo $total_inventory;
  ?&gt;
  </code></pre>
  
  <p>Why can't I just do this?</p>
  
  <pre><code>&lt;?php echo array_sum($category-&gt;products-&gt;inventory); ?&gt;
  </code></pre>
  
  <p>That results in an error: <code>PHP Notice: Trying to get property of non-object</code>.</p>
  
  <p>Then I thought maybe the following would work:</p>
  
  <pre><code>&lt;?php echo array_sum($category-&gt;products-&gt;getAttribute('inventory')); ?&gt;
  </code></pre>
  
  <p>However, that results in: <code>Fatal error: Call to a member function getAttribute() on a non-object</code>. </p>
  
  <p>Is it possible to use <code>array_sum()</code> in the way I'm attempting by just changing something slightly, or is it not possible because <code>$category-&gt;products</code> is actually an object, not an array? Is that right?</p>
  
  <p>I'm happy to be provided with articles or documentation that help explain what I'm missing.</p>
  
  <p>Thanks</p>