Jump to content

foreach loop in OOP


Recommended Posts

I'm a beginner currently studying Object Oriented Programming. The code in question is quite long so I will just share the snippet that I can't understand.

private $productlist = array();

public function addproduct($product){
$this->productlist[] = $product;

public function stockup(){
foreach($this->productlist as $product){

I'm sure that function addproduct adds product objects to the product list array. What does the foreach loop:


foreach($this->productlist as $product)


in the stockup function do? Does it take those values and store them back in $product?

Link to comment
Share on other sites

The foreach construct provides an easy way to iterate over arrays.




It is iterating over each item in $this->productlist (which appear to be product objects) so that you can reference it as $product and do something with it.    It appears that it is call the addstock() method on each object and adding 100 to the in stock quantity of each product, but we would need to see the addstock() function to tell.

Link to comment
Share on other sites


This topic is now archived and is closed to further replies.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.