我有一个在页面上显示广告的类。我想跟踪哪些广告已被显示,因此我添加了一个私有静态成员到将包含数字数组的类。我想将数据库查询结果中的ID添加到静态成员中,以便从下一个查询中排除这些ID。这会阻止显示的广告在同一页面上再次显示。PHP'试图通过静态类成员获取非对象的属性'
class ADS {
private static $excluded_ads = array();
function get_ads() {
// run db query and assign $ads to the resulting array
$ads = $this->query();
// Iterate through result and add the IDs of each row to the static array
foreach ($ads as $ad) {
self::$excluded_ads[] = $ad->ID;
}
}
function query() {
// Use local variable to hold string of excluded ads
$excluded_ads = $this->sql_get_excluded_ads();
// run the db query and use the class static member to exclude results
// SELECT * FROM ....
// WHERE ...
// AND p.ID NOT IN ($excluded_ads)
}
function sql_get_excluded_ads() {
if (empty(self::$excluded_ads)){
return '-1';
} else {
return implode(',',self::$excluded_ads);
}
}
}
$ads_class = new ADS();
$ads_class->get_ads();
当我加载页面我得到这个错误Trying to get property of non-object
为线self::$excluded_ads[] = $ad->ID;
做静态类成员以这种方式工作在PHP?我知道这个值会在每个页面加载时重置 - 但这是我想要的功能。我希望这只包含当前页面/过程的值,然后重置。
错误与你的静态变量无关,它与你的'$ ad'变量有关,它说它不是一个对象你确定query()返回一个对象数组? –
不应该在'query()'中使用'$ excluded_ads = sql_get_excluded_ads();''self :: $ excluded_ads = $ this-> sql_get_excluded_ads();' –
看起来您的查询结果并不符合您的期望。检查'var_dump($ ads);'的结果。 – BlitZ