abstract class Mother {
protected static $foo = null;
protected static $bar = null;
public function getFoo() { return static::$foo; }
public function getBar() { return static::$bar; }
public function setFoo($foo) { static::$foo = $foo; }
public function setBar($bar) { static::$bar = $bar; }
}
class Brother extends Mother {
protected static $foo = 'BROTHERS';
}
class Sister extends Mother {
protected static $foo = 'SISTERS';
}
$brother1 = new Brother();
$brother2 = new Brother();
$sister1 = new Sister();
$sister2 = new Sister();
$sister1->setBar('ONLY SISTERS'); // We set $bar = 'ONLY SISTERS' at sister1.
// We want only Sister instances to get this value...
// however Brother instances also get this value!
echo '<p>Brother 1: Foo="'.$brother1->getFoo().'", Bar="'.$brother1->getBar().'"</p>';
// Foo="BROTHERS", Bar="ONLY SISTERS"
echo '<p>Brother 2: Foo="'.$brother2->getFoo().'", Bar="'.$brother2->getBar().'"</p>';
// Foo="BROTHERS", Bar="ONLY SISTERS"
echo '<p>Sister 1: Foo="'.$sister1->getFoo().'", Bar="'.$sister1->getBar().'"</p>';
// Foo="SISTERS", Bar="ONLY SISTERS"
echo '<p>Sister 2: Foo="'.$sister2->getFoo().'", Bar="'.$sister2->getBar().'"</p>';
// Foo="SISTERS", Bar="ONLY SISTERS"
很顯然,如果每個孩子(兄弟姐妹)都沒有明確地重新定義靜態:: $ bar,他們的父母(母親)會爲他們設置值(或者至少對於那些沒有重新定義它的人)。PHP:將靜態變量範圍限制到特定的類
問題:有什麼辦法可以防止沒有重新定義static :: $ bar的孩子接收新值嗎?換句話說,如何確保只有被引用的類才能獲得新的值,即使靜態:: $ bar沒有在每個孩子中被明確地重新定義,也是如此?
我看到的只有一個選項來實現這一目標。你必須覆蓋姐妹類中的getBar和setBar方法。 setBar方法寫入$ this-> bar,getBar檢查是否設置了$ this-> bar,否則從parent :: $ bar中檢索。 – Dan 2012-03-02 20:26:49
當有對象實例時,是否有這些靜態的原因? – 2012-03-02 20:28:49
@丹你可能是對的。另一種選擇是在每個孩子中重新聲明static :: $ bar。問題是沒有辦法強迫程序員這樣做。 – mae 2012-03-02 20:42:32