I'm trying to work out how to check that a DataObject is populated before running it through a foreach loop. Here is what I came up with:
function LatestNews($num=5) {
$GetNews = DataObject::get("NewsPage", "ParentID = $this->ID", "DisplayDate DESC", "", $num);
$LatestNews = new DataObjectSet();
foreach(empty($GetNews)?array():$GetNews as $NewsItem){
$LongDate = date("l j F Y",strtotime($NewsItem->DisplayDate));
$extrainfo = array(
'ArticleTitle' => $NewsItem->Title,
'ArticleLink' => $NewsItem->Link(),
'DisplayDate' => $LongDate,
);
$LatestNews -> push(new ArrayData($extrainfo));
}
return $LatestNews;
}
As you can see I'm using
foreach(empty($GetNews)?array():$GetNews as $NewsItem)
so it gracefully fails if $GetNews is empty.
This works well in our development website but when I rolled it across to our production site it breaks with the following error when the DataObject is not empty - if the DataObject is empty I do not get an error:
[Notice] Trying to get property of non-object
Line 25 in /var/www/sites/wwwtasman/mysite/code/NewsListPage.php
25 $LongDate = date("l j F Y",strtotime($NewsItem->DisplayDate));
The only difference I can make up between the two websites is that our development website is running a slightly higher version of PHP (5.2.11) versus our production website (5.2.10).
All of this is pretty frustrating and I was wondering what tried and true method people use to make sure that if a DataObject is empty a foreach loop is not run.
Cheers
Tama