Php array initialization

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

$comment = array();

And when I add an element to an array

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

Here $cis an object of class Comment.

But when I try to access the functions of this class with $comment, I get the following error:

Fatal error: call member function getCommentString () for non-object

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

Thanks Sharmi

+3
source share
4 answers
$this->comment = array();
+3
source

Looks like a problem with an area.

$comments , $comments , $comments, .

, , $this->comments, $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;
    }
}
+2

This code can 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 how you add objects to the array (what is $ this-> comment referring to?), Or you can try to call → getCommentString () in the array, and not on the objects in the array itself.

0
source

You can see that in the array by passing it print_r():

print_r($comment);

Assuming you have objects Comment, you should be able to reference them using $comment[0]->getCommentString().

0
source

Source: https://habr.com/ru/post/1724033/


All Articles