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.
$c
But when I try to access the functions of this class with $comment, I get the following error:
$comment
Fatal error: call member function getCommentString () for non-object
Can someone tell me how to initialize an array of objects in php?
Thanks Sharmi
$this->comment = array();
Looks like a problem with an area.
$comments , $comments , $comments, .
$comments
, , $this->comments, $comments.
$this->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; } }
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.
You can see that in the array by passing it print_r():
print_r()
print_r($comment);
Assuming you have objects Comment, you should be able to reference them using $comment[0]->getCommentString().
Comment
$comment[0]->getCommentString()
Source: https://habr.com/ru/post/1724033/More articles:Practical COW program? - esoteric-languages | fooobar.comHow to declare a union in C #? - .netStandby Interaction with the iPhone - objective-cHow to clear Cursor.Clip in C # and let the cursor move freely? - c #Invalid server method methodname - javascriptJSF, several bean update properties on a form - javaHow do you represent the MineSweeper grid in Python? - pythonSML / NJ - dynamic type template - functional-programmingВыяснить индекс данного div в jQuery? - jquery.NET GDI +: rounded drawing lines - .netAll Articles