2009-11-26 130 views
3

我需要在PHP中初始化一个对象数组。 目前我有以下代码:php数组初始化

$comment = array(); 

,当我将一个元素增加到阵列

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

这里,$c是类注释的目的。

但是当我尝试使用$comment访问类的功能,我得到以下错误:

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

谁能告诉我如何初始化在php对象数组?

感谢 Sharmi

+2

您不能通过调用$ comment来访问变量$ this-> comment。 – William 2009-11-26 19:23:19

回答

3
$this->comment = array(); 
+0

如果初始化发生在构造函数之外,则不会 – Madbreaks 2013-12-04 01:17:31

0

此代码可以帮助你:

$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(); 
} 

我觉得你的问题是无论你如何添加对象的数组(什么是$这个 - >评论引用?),或者你可能试图在数组上调用 - > getCommentString()而不是数组中的实际对象。

0

你可以看到在数组中通过它传递给print_r()什么:

print_r($comment); 

假设你在那里有Comment对象,你应该能够$comment[0]->getCommentString()引用它们。

2

对我来说看起来像一个范围问题。

如果$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; 
    } 
}