3

I need to initialize an array of objects in PHP. Presently I have the following code:

$comment = array();

And when i am adding an element to the array

public function addComment($c){
    array_push($this->comment,$c);
}

Here, $c is an object of class Comment.

But when I try to access an functions of that class using $comment, I get the following error:

Fatal error: Call to a member function getCommentString() on a non-object

Can anyone tell me how to initialize an array of objects in php?

Thanks Sharmi

1
  • 2
    You can't access the variable $this->comment by calling $comment. Commented Nov 26, 2009 at 19:23

4 Answers 4

3
$this->comment = array();
Sign up to request clarification or add additional context in comments.

1 Comment

not if the initialization is happening outside of the constructor
2

Looks like a scope problem to me.

If $comments is a member of a class, calling $comments inside a function of that class will not actually use the member, but rather use an instance of $comments belonging to the scope of the function.

If other words, if you are trying to use a class member, do $this->comments, not just $comments.

class foo
{
    private $bar;

    function add_to_bar($param)
    {
        // Adds to a $bar that exists solely inside this
        // add_to_bar() function.
        $bar[] = $param;

        // Adds to a $bar variable that belongs to the
        // class, not just the add_to_bar() function.
        $this->bar[] = $param;
    }
}

Comments

0

This code might help you:

$comments = array();
$comments[] = new ObjectName(); // adds first object to the array
$comments[] = new ObjectName(); // adds second object to the array

// To access the objects you need to use the index of the array
// So you can do this:
echo $comments[0]->getCommentString(); // first object
echo $comments[1]->getCommentString(); // second object

// or loop through them
foreach ($comments as $comment) {
    echo $comment->getCommentString();
}

I think your problem is either how you are adding the objects to the array (what is $this->comment referencing to?) or you may be trying to call ->getCommentString() on the array and not on the actual objects in the array.

Comments

0

You can see what's in the array by passing it to print_r():

print_r($comment);

Presuming you have Comment objects in there, you should be able to reference them with $comment[0]->getCommentString().

Comments

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.