在這個例子中,我有一個抽象類和兩個常規類。抽象類不應該單獨使用,所以它的構造函數是受保護的。一些函數在抽象類中定義。PHP在對象之外可見的私有屬性(在同一個類中)
其中一個函數是一個「克隆」函數,它應該返回當前對象的新實例。 該函數複製當前對象。
這是我的問題:
當試圖在clone()中設置$ copy-> baz([2])時,它可以工作,因爲我在定義此私有屬性的類中。然而,這對我來說沒有意義(至少在這個例子中),因爲$ copy是另一個對象(同一個類) - 是否有可能迫使PHP使用魔術設置器(「設置私有屬性」)設置另一個對象(不是類)的私有屬性?
abstract class ac
{
private $baz = "fakedefault";
function __set($name, $value)
{
die("Setting private property!");
}
function clone()
{
$copy = clone $this; //make copy
//Test:
$this->baz = "newval"; //[1] Works as expected
$copy->baz = "newval"; //[2] Does not die!
return $copy; //return copy
}
}
class c1 extends ac
{
function foo()
{
print $this->baz;
}
}
class c2 extends ac
{
function foo()
{
print $this->baz;
}
}
function dostuff()
{
$o = new c1();
$o->baz = "thiswontwork"; //Private -> doesn't work
}
請查看我的回答我的最新編輯 - 我認爲這可能會有幫助。謝謝 –