Jump to content

foreach loop in OOP


spence911
Go to solution Solved by AbraCadaver,

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){
$product->addstock(100);
}

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

  • Solution

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

 

http://us2.php.net/manual/en/control-structures.foreach.php

 

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 thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.