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
$this->comment = array();
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.
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()
.
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;
}
}