鉴于您有一个包含不同数量对象的数组,您如何访问最后一个对象的属性?我试图用end($array);
,但它给人的错误:Object of class Post could not be converted to string
访问对象数组中最后一个对象的属性?
类是:
class Post {
private $datafile;
public $index;
public $subIndex;
public $poster;
public $title;
public $message;
public $date;
// constructor and some unrelated methods here
public function getCommentData($givenIndex) {
$comments = null;
$data = file($this->datafile);
foreach($data as $row) {
list($index, $subIndex, $poster, $message, $date) = explode('|', $row);
$this->index = $subIndex; // SubIndex ties a Comment to a Post (same ID)
if($this->index == $givenIndex) {
$comment = new Post();
$comment->poster = $poster;
$comment->message = $message;
$comment->date = date(DATEFORMAT, strtotime($date));
$comments[] = $comment;
}
}
return $comments;
}
}
现在,我想只能访问最后一个注释项目的属性,但我不知道应该如何做完了?在一个常规数组中,end()是快速且易于使用的,但是对于对象来说,它看起来不起作用?
下面是一个例子的var_dump:
array (size=2)
0 =>
object(Post)[4]
private 'datafile' => null
public 'index' => null
public 'subIndex' => null
public 'poster' => string 'Postaaja' (length=8)
public 'title' => null
public 'message' => string 'Kommentti' (length=9)
public 'date' => string '5 Mar 2013 | 23:12' (length=18)
1 =>
object(Post)[5]
private 'datafile' => null
public 'index' => null
public 'subIndex' => null
public 'poster' => string 'Toinenkin' (length=9)
public 'title' => null
public 'message' => string 'Lisäkommentti' (length=14)
public 'date' => string '5 Mar 2013 | 23:13' (length=18)
谢谢!
编辑: 这里是我试图使用它的方式:
$comments = new Post(FILECOMMENTS);
$currentComments = $comments->getCommentData($i); // $i is the index of current newspost item
$newsComments = new Format();
$newsComments->formatShortComment($currentComments, $i);
而且在格式类中的方法:
// This comment is displayed as a short text in the main News view
public function formatShortComment($data, $index) {?>
<div class="newsComments">
<p class="newsPreviewComment">
<?php
$lastItem = end($data);
if(!empty($lastItem->message)) {
echo '<i>"',$lastItem->message,'"</i> ';
echo '-',$lastItem->poster;
}
?></p>
» <a href="?page=comments&id=<?php echo $index; ?>">Show All/Add comments</a>
(<?php echo $commentCount; ?>)
</div><?php
}
请发布生成错误的代码。根据描述以及此处显示的内容,它应该在理论上起作用,但如果没有导致问题的代码,肯定无法确定。 – Adrian 2013-03-13 18:23:11
如何使用array_pop($ arrayofObjects); – Cups 2013-03-13 18:25:14
@Adrian:我将代码添加到文章 – 2013-03-13 18:32:55