다양한 양의 객체가 포함 된 배열이 있다고 가정하면 마지막 객체의 속성에 어떻게 액세스 할 수 있습니까? 나는 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()는 빠르고 쉽게 사용할 수 있지만 객체가 작동하지 않는 것처럼 보이는 것은 어떨까요?
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)
감사 :
여기 예제 위해서 var_dump입니다!
편집 :
// 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
어떻게 abt array_pop ($ arrayofObjects)를 사용하여; – Cups
@Adrian : 게시글에 코드를 추가했습니다. –