2013-03-13 2 views
1

Учитывая, что у вас есть массив, содержащий различные количества объектов, как вы можете получить доступ к свойствам последнего объекта? Я пытался использовать 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) 

Спасибо!

EDIT: Вот как я пытался использовать:

$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>&quot;',$lastItem->message,'&quot;</i> '; 
       echo '-',$lastItem->poster; 
      } 
     ?></p> 
     &raquo; <a href="?page=comments&amp;id=<?php echo $index; ?>">Show All/Add comments</a> 
     (<?php echo $commentCount; ?>) 
    </div><?php 
} 
+1

Пожалуйста, разместите код, создающий ошибку. Основываясь на описании и том, что показано здесь, он должен работать теоретически, но не может точно сказать, без кода, вызывающего проблему. – Adrian

+1

Как abt использовать array_pop ($ arrayofObjects); – Cups

+1

@Adrian: Я добавил код к сообщению –

ответ

0

Вы можете попробовать:

$tempArray = array_values($data); 

$lastItem = $tempArray[count($tempArray)-1]; 
0

I надеюсь, что я не пропустил что-то важное, но если вы просто пытаетесь получить последний элемент массива PHP:

$lastItem = $data[count($data) - 1];