0

I create instances of the same class with inside a for loop. But it seems that these instances refer the same object somehow.

Here is the code;

class Content{
    /**
     * current content id
     * @var int 
     */
    public $id;

    function __construct($id){
        echo " <br>Construct content ".$id;
    }

    function createContentOfPage($id){
        $contentIdArray = $this->dbo->getContentIdsForPage($id);
        /*var_dump of $contentIdArray aray is given below*/
        if(is_array($contentIdArray) && count($contentIdArray)>0){
        $contentArray = array();    
            foreach ($contentIdArray as $Id){
                echo "<br>Content id: ".$Id['content_id'];
                array_push($contentArray, new Content(($id['content_id'])));
            }

        }
    }
}

Here is the var_dump of $contentIdArray

array(2) {
  [0]=>
  array(1) {
    ["content_id"]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    ["content_id"]=>
    string(1) "2"
  }
}

If I run the createContentOfPage() here is the out put;

Content id: 1 
Construct content 1
Content id: 2 
Construct content 1

What is that I'm doing wrong in here? Please help.

1
  • 1
    You're sure to confuse someone by using $Id, $id, and a member variable $id at the same time. Commented Mar 18, 2013 at 11:48

1 Answer 1

1

Well, you're using different ID variables:

echo "<br>Content id: ".$Id['content_id'];
array_push($contentArray, new Content(($id['content_id'])));

Use either $Id or $id consistently — in this case, you need to use $Id.


You should avoid the practice of shadowing variables like this. Call the array iterator variable $contentId and your parameter $pageId, or something like that.

Sign up to request clarification or add additional context in comments.

1 Comment

ok! now I'm feeling like a retard for my self... :(( Thank you soo much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.