簡體   English   中英

PHP“嘗試獲取非對象的屬性”和靜態類成員

[英]PHP 'Trying to get property of non-object' with static class member

我有一堂課在頁面上顯示廣告。 我想跟蹤顯示了哪些廣告,因此我向該類添加了一個私有的靜態成員,該成員將容納數字數組。 我想將數據庫查詢結果中的ID添加到靜態成員中,作為從下一個查詢中排除這些ID的一種方式。 這樣可以防止所顯示的廣告再次顯示在同一頁面上。

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;這行Trying to get property of non-object self::$excluded_ads[] = $ad->ID;

靜態類成員在PHP中是否以這種方式工作? 我知道此值將在每次頁面加載時重置-但這就是我想要的功能。 我希望它只包含當前頁面/進程的值,然后重置。

您是否嘗試調試var_dump($ ads)中的內容?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM