2010-03-04 25 views
2

我可能會問這個問題很糟糕,所以我會舉一個例子。我有一類就是類似這樣的東西:有沒有辦法設置一個類變量應用於該類的所有實例在PHP?

class myclass { 
    var $template = array(); 
    var $record = array(); 

function __construct($template,$record) { 
    $this->template = (set = to a database response here); 
    $this->record = (set = to a database response here); 
} 

使用該對象時,我的問題是,模板應始終是相同的,記錄是爲對象的每個實例有什麼變化。有沒有辦法讓$ template的值繼承每個新實例?類似於

$a = new myclass(1,500); 
$b = new myClass(2); 

其中b的值爲創建$ a時已經生成的$this->template。也許我完全從錯誤的角度來看待這個問題。任何建議感激。

回答

3

是的。 Declaring it static將使它成爲一個類屬性

class Counter { 
    public static $total = 0; 
    public function increment() 
    { 
     self::$total++; 
    } 
} 
echo Counter::$total; // 0; 
$a = new Counter; 
$a->increment(); 
echo $a::$total; // 1; 
$b = new Counter; 
echo $b::$total; // 1; 

注:我用$ a和$ b訪問靜態屬性,以表明屬性適用於這兩種情況下simultaenously點。而且,這樣做只能從5.3開始。在此之前,你必須做Counter :: $ total。

+0

你或許應該提到它如何被訪問;) – 2010-03-04 14:13:29

+0

Oookay,但我不是一個靜態變量設置爲我需要爲了得到信息從數據庫的功能。 – Stomped 2010-03-04 14:14:31

+0

「爲函數設置一個靜態變量」,這是什麼意思,以及如何與數據庫相關? – 2010-03-04 14:17:06

相關問題